迭代QTreeView行

时间:2019-01-29 22:44:04

标签: python

我将如何修改下面的函数以仅遍历QTreeview中的行而不遍历每一行和每一列? 在遍历每一行时,我想获取第二列的UserRole和DisplayRole数据。

enter image description here

我已经接近迭代部分,但是我不确定如何访问第二列的UserRole和Display Role。

import sys, random
from PySide import QtGui, QtCore


class Browser(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Browser, self).__init__(parent)
        self.resize(300, 400)

        self.uiItems = QtGui.QTreeView()
        self.uiItems.setAlternatingRowColors(True)
        self.uiItems.setSortingEnabled(True)
        self.uiItems.sortByColumn(0, QtCore.Qt.AscendingOrder)
        self.uiItems.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.proxyModel = QtGui.QSortFilterProxyModel()
        self.proxyModel.setSourceModel(QtGui.QStandardItemModel())
        self.proxyModel.setDynamicSortFilter(True)
        self.uiItems.setModel(self.proxyModel)

        self.button = QtGui.QPushButton('Print')

        grid = QtGui.QVBoxLayout(self)
        grid.addWidget(self.uiItems)
        grid.addWidget(self.button)

        self.populate()
        self.button.clicked.connect(self.printData)


    def populate(self):
        items = ['Cookie','Hummus','Spaghetti','Candy','Chocolate']
        subitems = ['Sweet','Caramel','Sucker','Apple']

        model = self.proxyModel.sourceModel()
        model.clear()
        model.setHorizontalHeaderLabels(['Name', 'Count'])

        for item in items:
            count = random.randint(0,3)
            col1 = QtGui.QStandardItem(item)
            # col2 = QtGui.QStandardItem(str(count))

            # subitems:
            for i in range(count):
                child1 = QtGui.QStandardItem(subitems[random.randint(0,3)])
                child2 = QtGui.QStandardItem(str(random.randint(0,20)))
                col1.appendRow([child1, child2])

            model.appendRow([col1])

        self.uiItems.expandAll()
        self.uiItems.header().setResizeMode(QtGui.QHeaderView.ResizeToContents)


    def iterItems(self, root):
        if root is not None:
            stack = [root]
            while stack:
                parent = stack.pop(0)
                for row in range(parent.rowCount()):
                    for column in range(parent.columnCount()):
                        child = parent.child(row, column)
                        yield child
                        if child and child.hasChildren():
                            stack.append(child)


    def printData(self):
        for x in self.iterItems(self.proxyModel.sourceModel().invisibleRootItem()):
            print x


def main():
    app = QtGui.QApplication(sys.argv)
    ex = Browser()
    ex.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:1)

def iterItems(self, root):
    if root is not None:
        for row in range(root.rowCount()):
            row_item = root.child(row, 0)
            if row_item.hasChildren():
                for childIndex in range(row_item.rowCount()):
                    # Take second column from "child"-row
                    child = row_item.child(childIndex, 1)
                    yield child



def printData(self):
    for x in self.iterItems(self.proxyModel.sourceModel().invisibleRootItem()):
        print x.data(role=QtCore.Qt.DisplayRole), x.data(role=QtCore.Qt.UserRole)

答案 1 :(得分:0)

如果它对您有用,那么QTreeWidgetItemIterator可能会容易得多:

def iterTreeItems(tree)
  iterator = QtWidgets.QTreeWidgetItemIterator(tree)
  item: QtWidgets.QTreeWidgetItem = iterator.value()
  while item is not None:
    yield item
    iterator += 1
    item = iterator.value()