Iterate through the contents of rows selected from a QTableView QSqlQueryModel?

I’m going through the “Querying SQL databases with Qt models” chapter of the PySide2 edition of the book. I need something like the “databases\tableview_querymodel.py” sample. And then a button, that should perform something based on the contents of the rows selected by the user from that tableview.

So, how can I get the rows that were selected by the user from that tableview and then iterate through the contents of those selected rows?

Thanks in advance!

I found the answer. On my self.table = QTableView() I need to do this the retrieve the rows selected by the user:

indexes = self.table.selectionModel().selectedRows()

and then for example to print the contents of the 2nd column of the selected rows:

for index in indexes:
            print(self.table.model().data(self.table.model().index(index.row(), 1)))

Hey @luis yep that will do it. I’d take a reference to the model object first just to simplify the code a bit

model = self.table.model()
for index in indexes:
            print(model.data(model.index(index.row(), 1)))

Note, that in your .data method the second param 1 is Qt.DecorationRole – not sure if this is what you intended? If you want to get the content you would use Qt.DisplayRole (which == 0) (see roles enum in the documentation). Ignore this my eyes were wonky with the brackets.

Also … I was looking at the selectedRows method though and noticed that it actually accepts a parameter column which (slightly confusingly) is the value it uses for the column in the returned indexes.

Since you want the values in column 2, you can simplify a bit by passing that column number to selectedRows directly… it then returns the exact indexes you want.

indexes = self.table.selectionModel().selectedRows(column=2)
model = self.table.model()
role = Qt.DisplayRole # or Qt.DecorationRole
for index in indexes:
    print(model.data(index, role))

1 Like

Much cleaner! Thanks for the hints.

edit: and in my code, the 1 in index.row(), 1 is needed to access the data of the second column. 0 gives me the 1st column, 2 would be the 3rd and so on.

Great, glad it helped! I think this is a good candidate to add tutorial about, common to want to find what is selected in a table.

Ha, quite right – got confused among all the brackets :smiley:

2 Likes