pythonpyqtpyqt4qstandarditemmodel

Iterate over rows of QTableView


I have a QTableView showing the children of a specific QModelIndex in my model (which has hierarchical data, which the table cannot of course show). I want to be able to iterate over all items in the table view, i.e. all children of the rootIndex. How can I efficiently do this? I have a reference to the parent index with table.rootIndex(), however I don't see any way of iterating over the children of an index without iterating over the whole entire model, which just seems wrong.

Is this a job for a QSortFilterProxyModel to install a sub-set of the model in the table? Does what I just said even make sense?!

Here's a quick sample to get up and running

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)

Solution

  • Okay I feel dumb, I figured it out. Forgot that model.index() allows you to specify a parent... I suppose some other poor soul out there might get as confused as I just was so here you go:

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