python - QTreeWidget - 从排序中排除顶级项目

标签 python sorting pyqt pyqt4 qtreewidget

我有一个 2 级 QTreeWidget。顶层只有一列,仅用于对第二层进行分组,第二层保存实际的多列数据。

当我通过单击标题(或任何其他方式,真的)进行排序时,我只想对第二级进行排序,因为顶级项目在应用程序的其他地方设置了固定顺序,不应该受影响。

我如何实现这一目标?

最佳答案

最简单的解决方案是创建QTreeWidgetItem 的子类并重新实现其__lt__ 方法,以便它始终返回False。 Qt 使用稳定的排序算法,所以这意味着项目将始终保持其原始顺序。此子类应仅用于顶级项目。

这是一个似乎符合您的规范的工作演示:

import sys
from random import randint
from PyQt4 import QtCore, QtGui

class TreeWidgetItem(QtGui.QTreeWidgetItem):
    def __lt__(self, other):
        return False

class Window(QtGui.QTreeWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.setHeaderLabels('Name X Y'.split())
        for text in 'One Two Three Four'.split():
            parent = TreeWidgetItem([text])
            for text in 'Red Blue Green Yellow'.split():
                child = QtGui.QTreeWidgetItem([
                    text, str(randint(0, 9)), str(randint(0, 9))])
                parent.addChild(child)
            self.addTopLevelItem(parent)
        self.expandAll()
        self.setSortingEnabled(True)
        self.sortByColumn(0, QtCore.Qt.AscendingOrder)

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(800, 100, 320, 400)
    window.show()
    sys.exit(app.exec_())

关于python - QTreeWidget - 从排序中排除顶级项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39318827/

相关文章:

r - 将列中的唯一值更改为两个特定值之一

r - 在 R 中按特定顺序对数据进行排序

python - 如何在 ListView 中选择行

python - 使用 zipfile python 更改文件名

python - 你如何让 argparse 选择默认的子解析器?

Python - 循环遍历一个字符串

python - 将 RoleNeed 与 Flask Principal 相结合

python - 排列矩形的顶点

python - 如何调试基于 PyQt4 的应用程序?

python - 如何在 Qlistview 中获取选中的项目?