Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select multiple rows in QTableWidget?

I have a table where I've enabled ExtendedSelection:

table.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)

When I close the UI I use QSettings to remember any selected rows. When I re-open my UI I want it to automatically re-select the rows automatically.

I have this, but this ends up only selecting the last selected row:

QSETTINGS = [1, 2, 3]  # Indicates row 1, 2 and 3 should be selected

for row in xrange(table.rowCount()):
    table_item = table.item(row, 1)
    row_data = table_item.data(QtCore.Qt.UserRole)
    row_id = row_data
    if row_id in QSETTINGS:
        table.selectRow(row)  # This ends up only making one row selected

What should I use instead of table.selectRow(row) in order to make sure to select more than just one row?


Edit

In my original question, I said I was using QtGui.QAbstractItemView.MultiSelection. However, I'm not. I'm using QtGui.QAbstractItemView.ExtendedSelection, which is also why my row selection code obviously doesn't work. By temporarily switching to MultiSelection, selecting the rows and then switch back to ExtendedSelection, the code in my question works great.

like image 953
fredrik Avatar asked Oct 29 '25 11:10

fredrik


1 Answers

By temporarily setting MultiSelection selection mode, each row is selected.

QSETTINGS = [1, 2, 3]  # Indicates row 1, 2 and 3 should be selected

# Temporarily set MultiSelection
table.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)

for row in xrange(table.rowCount()):
    table_item = table.item(row, 1)
    row_data = table_item.data(QtCore.Qt.UserRole)
    row_id = row_data
    if row_id in QSETTINGS:
        table.selectRow(row)  # This ends up only making one row selected

# Revert MultiSelection to ExtendedSelection
table.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
like image 74
fredrik Avatar answered Nov 01 '25 02:11

fredrik