python - 如何在 QTableWidget 中选择多行?

标签 python pyqt4 pyside pyqt5

我有一张启用了 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/

相关文章:

python - 如何从另一个 python 文件调用 Qt Thread (QThread)? (QThread被销毁)

python - 如何通过 QStateMachine addtransition 使用自定义信号

python - 使用 QSignalMapper 和实例方法将 PySide 连接到信号

python - 从文本段获取 QTreeview 索引

python - django 中的 Modelformset 泛型 CreateView 和 UpdateView

python - 从 QGraphicsView 转到 QMainWindow 现在 keyPressEvent 看不到箭头键

python - 解释器交互模式的目的是保持文件打开

python - 如何在 PySide 中发出以 self 作为参数的信号?

python - pytest 属性错误 : 'Function' object has no attribute 'get_marker'

python - 设置 Pandas 索引或转置