Search code examples
c++qtqtreewidget

sort qtreewidget toplevel item base on a child data


i have a qtreewidget with toplevelitems. each toplevelitem has 4 childeren, each child has special value, first child of all toplevelitems is its parrent cost, i want to sort this toplevelitems base on this cost, but i don't know how to do this? my idea is to keep this toplevelitems and their cost in a map and add and take them each time a toplevelitem is added, but i'm looking for a better way. thanks in advance.


Solution

  • By default, tree widget sorts items according to their texts, however you can change it by overriding the operator<() of the QTreeWidgetItem. Below is the example of custom QTreeWidgetItem with specific operator (see comments):

    class TreeWidgetItem : public QTreeWidgetItem
    {
    public:
        // The constructors. Add more, if needed.
        TreeWidgetItem(QTreeWidget *parent, const QStringList &strings,
                       int type = Type)
            : QTreeWidgetItem(parent, strings, type)
        {}
    
        TreeWidgetItem(QTreeWidgetItem *parent, const QStringList &strings,
                       int type = Type)
            : QTreeWidgetItem(parent, strings, type)
        {}
    
        // Compares two tree widget items. The logic can be changed.
        bool operator<(const QTreeWidgetItem& other) const
        {
            // Get the price - the first child node
            int price1 = 0;
            if (childCount() > 0)
            {
                QTreeWidgetItem *firstChild = child(0);
                price1 = firstChild->text(0).toInt();
            }
    
            // Get the second price - the first child node
            int price2 = 0;
            if (other.childCount() > 0)
            {
                QTreeWidgetItem *firstChild = other.child(0);
                price2 = firstChild->text(0).toInt();
            }
            // Compare two prices.
            return price1 < price2;
        }
    };
    

    And here is how this class can be used with QTreeWidget:

    // The sortable tree widget.
    QTreeWidget tw;
    tw.setSortingEnabled(true);
    QTreeWidgetItem *item1 = new TreeWidgetItem(&tw, QStringList() << "Item1");
    QTreeWidgetItem *child1 = new TreeWidgetItem(item1, QStringList() << "10");
    
    QTreeWidgetItem *item2 = new TreeWidgetItem(&tw, QStringList() << "Item2");
    QTreeWidgetItem *child2 = new TreeWidgetItem(item2, QStringList() << "11");    
    tw.show();