如何在启用排序的情况下反转QTableView选择

时间:2018-04-04 23:02:55

标签: python qt pyqt qtableview selectionmodel

以下代码会创建一个QTableView,其中包含QPushButton

enter image description here

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
app = QApplication([])    

class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setLayout(QVBoxLayout())
        self.view = QTableView(self)
        self.view.setSelectionBehavior(QTableWidget.SelectRows)
        self.view.setSortingEnabled(True)
        self.view.sortByColumn(0, Qt.DescendingOrder)

        self.view.setModel(QStandardItemModel(4, 4))
        for each in [(row, col, QStandardItem('item %s_%s' % (row, col))) for row in range(4) for col in range(4)]:
            self.view.model().setItem(*each)

        self.layout().addWidget(self.view)

        btn1 = QPushButton('Invert selection')
        btn1.clicked.connect(self.invertSelection)
        self.layout().addWidget(btn1)
        self.resize(500, 250)
        self.show()

    def invertSelection(self):
        model = self.view.model()
        for i in range(model.rowCount()):
            for j in range(model.columnCount()):
                ix = model.index(i, j)
                self.view.selectionModel().select(ix, QItemSelectionModel.Toggle)


dialog = Dialog()
app.exec_()

...

第1步: 通过单击其任何单元格选择最后一行。单击的行突出显示为蓝色,表示现在已选中:

enter image description here

第2步: 单击“反转选择”按钮。选择正确反转:

enter image description here

第3步: 现在单击列标题#4以按最后一列排序。此时选择被打破(只选择了一个单元格并且它被移动了): enter image description here

问题:如何解决问题?

0 个答案:

没有答案