迭代QTableVi的行

2024-10-06 15:18:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个QTableView,显示模型中特定QModelIndex的子级(它有层次数据,表当然不能显示这些数据)。我希望能够迭代表视图中的所有项,即rootIndex的所有子项。我怎样才能有效地做到这一点?我有一个关于父索引的引用表.rootIndex(),但是我看不到任何迭代索引的子级而不迭代整个模型的方法,这似乎是错误的。在

这是QSortFilterProxyModel在表中安装模型的子集的任务吗?我刚才说的有道理吗?!在

这里有一个快速启动和运行的示例

class Sample(QtGui.QDialog):
    def __init__(self):
    super(Sample, self).__init__()
        model = QtGui.QStandardItemModel(self)

        parent_index1 = QtGui.QStandardItemModel("Parent1")
        model.appendRow(parent_index1)

        parent_index2 = QtGui.QStandardItemModel("Parent2")
        model.appendRow(parent_index2)

        one = QtGui.QStandardItem("One")
        two = QtGui.QStandardItem("Two")
        three = QtGui.QStandardItem("Three")

        parent_index1.appendRows([one, two, three])

        table = QtGui.QTableView(self)
        table.setModel(model)
        table.setRootIndex(model.index(0,0))

        # okay now how would I loop over all 'visible' rows in the table? (children of parent_index1)

Tags: 数据sample模型selfmodelinittableparent
2条回答

以下是两种迭代QTableView的方法:

假设table_view是对QTableView接口对象的引用,并且已经在其中填充了项。如果用户已经选择/单击了项,则可以通过以下方式进行迭代:

for item in table_view.selectedIndexes():
    #whatever you want to do with the data in that cell is now up to you
    table_cell_value = item.data()
    print(table_cell_value)

但是,如果用户没有选择任何内容,而是希望遍历表中的所有项,则只需进行一个小的调整:

^{pr2}$

好吧,我觉得很傻,我想出来了。忘记了model.index()允许您指定父级。。。我想其他可怜的人可能会和我一样困惑,所以你来吧:

for row in range(self.model.rowCount(self.table.rootIndex())):
    child_index = self.model.index(row, 0, self.table.rootIndex())) # for column 0

相关问题 更多 >