如何select QTableWidget 的多个单元格?

How to select multiple cells of QTableWidget?

我正在尝试从 QTableWidget 预 select 多个 "individual values (or cells some would like to call em)",但我似乎无法找到正确的方法。我已经尝试了 setRangeSelect、selectRow & selectColumn,并且 none 的方法有效。

寻求帮助。 (请看我尝试做的测试方法)

import sys
import json
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QPushButton
from PyQt5.Qt import QTableWidgetItem, QAbstractItemView

class Demo(QWidget):

    def __init__(self):
        super().__init__()
        self.rowTracker = []
        self.initUI()
        self.initQTableWidget()

    def initUI(self):       
        self.resize(600, 600)
        # populate some data
        self.rows = [['a1','b1', 'c1'], ['a2','b2','c2'], ['a3','b3','c3'], ['a4','b4','c4'], ['a5','b5','c5']]

        self.btn = QPushButton(self)
        self.btn.move(50, 250)
        self.btn.resize(150, 40)
        self.btn.setText('Check')
        self.btn.clicked.connect(self.test)

    def initQTableWidget(self):
        self.tableWidget = QTableWidget(self)
        self.tableWidget.resize(self.width(), self.height()-400)
        self.tableWidget.setRowCount(len(self.rows))
        self.tableWidget.setColumnCount(len(self.rows[0]))

        # here we will change row selection behavior to multiselection
        self.tableWidget.setSelectionMode(QAbstractItemView.MultiSelection)

        for row in enumerate(self.rows):
            # print(row)
            for col in enumerate(row[1]):
                item = QTableWidgetItem()
                item.setText(col[1])
                self.tableWidget.setItem(row[0], col[0], item)

    def test(self):
        # print(dir(self.tableWidget))
        self.tableWidget.select('<2nd row>', '<1st column>')

        self.tableWidget.select('<3nd row>', '<2nd column>')
        # self.tableWidget.setRangeSelect()

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

有以下方法:

  1. setSelected() method of QtableWidgetItem:
self.tableWidget.item(1, 0).setSelected(True)
self.tableWidget.item(2, 1).setSelected(True)
  1. select() method of QItemSelectionModel:
model = self.tableWidget.model()
selection_model = self.tableWidget.selectionModel()
selection_model.select(model.index(1, 0), QItemSelectionModel.Select)
selection_model.select(model.index(2, 1), QItemSelectionModel.Select)

第二种方法适用于所有继承自第二种方法 QAbstractItemView, and the first method is just a wrapper that makes QTableWidget 的视图。