如何在QTableWidget中选择多行?

时间:2016-06-17 14:45:28

标签: 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,我的问题中的代码效果很好。

3 个答案:

答案 0 :(得分:3)

通过临时设置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)

答案 1 :(得分:1)

您需要在每个setSelected

上使用QTableWidgetItem
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:
        for col in table.columnCount():
            item = table.item(row, col)
            if item:
                item.setSelected(True)

答案 2 :(得分:0)

在此示例中table.selectRow(i)正在进行多选:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class MyTableWidget(QtWidgets.QTableWidget):
    def __init__(self, parent = None):
        QtWidgets.QTableWidget.__init__(self, parent)
        self.setRowCount(5)
        self.setColumnCount(3)
        self.items = [['a1','b1', 'c1'], ['a2','b2','c2'], ['a3','b3','c3'], ['a4','b4','c4'], ['a5','b5','c5']]
        self.hh = ['a', 'b','c']
        self.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
        selected = [1,2,4]
        self.setSel(selected)

        for r in range(0,len(self.items)):
            for c in range(0,len(self.items[0])):
                item = QtWidgets.QTableWidgetItem()
                item.setText(self.items[r][c])
                item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable)
                self.setItem(r,c,item)

    def setSel(self, selection):
        for i in selection:
            self.selectRow(i)

app = QtWidgets.QApplication(sys.argv) 
widget = MyTableWidget()
widget.show()
sys.exit(app.exec_())

如果我在设置选择后调用setSelectionMode

,我会得到您描述的行为