我有一张启用了 ExtendedSelection 的表格:
table.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
当我关闭 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
我应该使用什么来代替 table.selectRow(row)
以确保选择不止一行?
编辑
在我最初的问题中,我说我使用的是 QtGui.QAbstractItemView.MultiSelection
。然而,我不是。我正在使用 QtGui.QAbstractItemView.ExtendedSelection
,这也是我的行选择代码显然不起作用的原因。通过暂时切换到 MultiSelection
,选择行然后切换回 ExtendedSelection
,我的问题中的代码效果很好。
最佳答案
通过临时设置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)
关于python - 如何在 QTableWidget 中选择多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37884480/