【问题标题】:sort qtreewidget toplevel item base on a child data根据子数据对 qtreewidget 顶级项目进行排序
【发布时间】:2014-05-21 06:20:25
【问题描述】:

我有一个qtreewidgettoplevelitems。每个toplevelitem 有4 个childeren,每个孩子都有特殊价值,所有顶级物品的第一个孩子是它的父母成本,我想sort 这个toplevelitems 基于这个成本,但我不知道该怎么做这?我的想法是在每次添加toplevelitem 时将其保留在mapmaptake 中,但我正在寻找更好的方法。 提前致谢。

【问题讨论】:

    标签: c++ qt qtreewidget


    【解决方案1】:

    默认情况下,树小部件根据文本对项目进行排序,但是您可以通过覆盖QTreeWidgetItem 的运算符QTreeWidgetItem 示例(参见 cmets):

    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;
        }
    };
    

    下面是这个类如何与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();
    

    【讨论】:

      猜你喜欢
      • 2017-01-12
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      相关资源
      最近更新 更多