The code below creates a single QTableView
with a QPushButton
:
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_()
....
Step 1: Select the last row by clicking on any of its cells. The clicked row is highlighted blue to indicate it is now selected:
Step 2: Click "Invert selection" button. The selection is properly inverted:
Step 3:
Now click on column header #4 to sort by last column. At this point the selection is broken (there is only one cell is selected and it is shifted wild):
Question: How to fix the issue?