如何在QTableWidget中选择多行?

fre*_*rik 2 python pyqt4 pyside pyqt5

我有一个启用了 ExtendedSelection 的表:

table.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
Run Code Online (Sandbox Code Playgroud)

当我关闭 UI 时,我使用 QSettings 来记住任何选定的行。当我重新打开我的 UI 时,我希望它自动重新选择行。

我有这个,但这最终只选择了最后选择的行:

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
Run Code Online (Sandbox Code Playgroud)

table.selectRow(row)为了确保选择不止一行,我应该使用什么?


编辑

在我最初的问题中,我说我正在使用QtGui.QAbstractItemView.MultiSelection. 然而,我不是。我正在使用QtGui.QAbstractItemView.ExtendedSelection,这也是为什么我的行选择代码显然不起作用的原因。通过暂时切换到MultiSelection,选择行然后切换回ExtendedSelection,我的问题中的代码效果很好。

fre*_*rik 5

通过临时设置MultiSelection选择模式,选择每一行。

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)
Run Code Online (Sandbox Code Playgroud)