列出所有QtreeWidget层次结构

时间:2018-12-06 23:38:54

标签: python pyqt pyside qtreewidget

我有一个列出的QTreeWidget

  column 0   |  column 1   |column 2
-----------------------------------

    file1
      +      | found item  | (checkbox) new item
      +      | found item  | (checkbox) new item 
    file2
      +      | found item  | (checkbox) new item
             | found item  | (checkbox) new item 

我正在寻找一种方法,当用户按下按钮时显示所有数据,如果未选中新项目,则会跳过该行。

我发现了与here之后类似的内容,但这仅打印已选中/未选中的项目。我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

想法是遍历项目并验证条件:

from PyQt4 import QtCore, QtGui
import random

class Widget(QtGui.QWidget):
    def __init__(self):
        super(Widget, self).__init__()
        self.tree = QtGui.QTreeWidget(columnCount=3)
        self.tree.setHeaderLabels(["column {}".format(i) for i in range(3)])
        button = QtGui.QPushButton("Press Me", 
            clicked=self.on_clicked)
        lay = QtGui.QVBoxLayout(self)
        lay.addWidget(self.tree)
        lay.addWidget(button)
        self.create_data()
        self.resize(640, 480)

    def create_data(self):
        for i in range(4):
            it = QtGui.QTreeWidgetItem(["file{}".format(i)])
            self.tree.addTopLevelItem(it)
            for j in range(random.randint(2, 5)):
                vals = ["+", "found item-{}-{}".format(i, j), "new item-{}-{}".format(i, j)]
                child_it = QtGui.QTreeWidgetItem(vals)
                child_it.setCheckState(2, random.choice([QtCore.Qt.Checked, QtCore.Qt.Unchecked]))
                it.addChild(child_it)
        self.tree.expandAll()

    @QtCore.pyqtSlot()
    def on_clicked(self):
        d = dict()
        for i in range(self.tree.topLevelItemCount()):
            top_item = self.tree.topLevelItem(i)
            v = []
            for j in range(top_item.childCount()):
                child_item = top_item.child(j)
                if child_item.checkState(2) == QtCore.Qt.Checked:
                    v.append(tuple(child_item.text(i) for i in (1, 2)))
            d[top_item.text(0)] = v
        print(d)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

输出:

enter image description here

{'file0': [('found item-0-2', 'new item-0-2'), ('found item-0-3', 'new item-0-3')], 'file1': [('found item-1-0', 'new item-1-0'), ('found item-1-1', 'new item-1-1'), ('found item-1-2', 'new item-1-2')], 'file2': [('found item-2-0', 'new item-2-0'), ('found item-2-1', 'new item-2-1'), ('found item-2-3', 'new item-2-3')], 'file3': [('found item-3-0', 'new item-3-0'), ('found item-3-1', 'new item-3-1')]}