1 /* tree_model_helpers.h
2  *
3  * Utility template classes for basic tree model functionality
4  *
5  * Wireshark - Network traffic analyzer
6  * By Gerald Combs <gerald@wireshark.org>
7  * Copyright 1998 Gerald Combs
8  *
9  * SPDX-License-Identifier: GPL-2.0-or-later
10  */
11 
12 #ifndef TREE_MODEL_HELPERS_H
13 #define TREE_MODEL_HELPERS_H
14 
15 #include <config.h>
16 #include <ui/qt/utils/variant_pointer.h>
17 
18 #include <QAbstractItemModel>
19 
20 //Base class to inherit basic tree item from
21 template <typename Item>
22 class ModelHelperTreeItem
23 {
24 public:
ModelHelperTreeItem(Item * parent)25     ModelHelperTreeItem(Item* parent)
26         : parent_(parent)
27     {
28     }
29 
~ModelHelperTreeItem()30     virtual ~ModelHelperTreeItem()
31     {
32         for (int row = 0; row < childItems_.count(); row++)
33         {
34             delete VariantPointer<Item>::asPtr(childItems_.value(row));
35         }
36 
37         childItems_.clear();
38     }
39 
appendChild(Item * child)40     void appendChild(Item* child)
41     {
42         childItems_.append(VariantPointer<Item>::asQVariant(child));
43     }
44 
prependChild(Item * child)45     void prependChild(Item* child)
46     {
47         childItems_.prepend(VariantPointer<Item>::asQVariant(child));
48     }
49 
50 
insertChild(int row,Item * child)51     void insertChild(int row, Item* child)
52     {
53         childItems_.insert(row, VariantPointer<Item>::asQVariant(child));
54     }
55 
removeChild(int row)56     void removeChild(int row)
57     {
58         delete VariantPointer<Item>::asPtr(childItems_.value(row));
59         childItems_.removeAt(row);
60     }
61 
child(int row)62     Item* child(int row)
63     {
64         return VariantPointer<Item>::asPtr(childItems_.value(row));
65     }
66 
childCount()67     int childCount() const
68     {
69         return childItems_.count();
70     }
71 
row()72     int row()
73     {
74         if (parent_)
75         {
76             return parent_->childItems_.indexOf(VariantPointer<Item>::asQVariant((Item *)this));
77         }
78 
79         return 0;
80     }
81 
parentItem()82     Item* parentItem() {return parent_; }
83 
84 protected:
85     Item* parent_;
86     QList<QVariant> childItems_;
87 };
88 
89 #endif // TREE_MODEL_HELPERS_H
90