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?
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))
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.
Also, you can apparently do something like:
"self.myQSQLTableModel.record(integer).value(“myFieldName”)
I’m trying to use this because it allows reference by name. I hate using positional reference to a sql record, because it breaks if I find myself having to add or delete fields. This apparently acts through the model, whereas your solution Martin acts through the TableView. Since I’m a newbie with QT, I have not yet figured out when I should be using the model, and when the view.
and of course, Martin, in your example I can use fieldIndex to get the value by name, like this:
indexes = self.utterancesTable.selectionModel().selectedRows(column=self.model.fieldIndex(“UID”))