Skip to content

Instantly share code, notes, and snippets.

@MaurizioB
Created June 12, 2021 00:21
Show Gist options
  • Save MaurizioB/f1f39bbba6c3819dc3c3543b556c0fbb to your computer and use it in GitHub Desktop.
Save MaurizioB/f1f39bbba6c3819dc3c3543b556c0fbb to your computer and use it in GitHub Desktop.
QAbstractTableModel item selection odd behavior when moving columns
try:
from PySide2 import QtCore, QtWidgets
print(QtCore.__version__)
except:
from PyQt5 import QtCore, QtWidgets
print(QtCore.QT_VERSION_STR)
class Model(QtCore.QAbstractTableModel):
def __init__(self,):
super().__init__()
self._data = []
for r in range(5):
row = []
self._data.append(row)
for c in range(5):
row.append((r, c))
def columnCount(self, parent=None):
return len(self._data[0])
def rowCount(self, parent=None):
return len(self._data)
def data(self, index, role=QtCore.Qt.DisplayRole):
if role == QtCore.Qt.DisplayRole:
return '{} {}'.format(
*self._data[index.row()][index.column()])
def moveColumn(self, source, dest):
target = dest
if dest > source:
target += 1
self.beginMoveColumns(QtCore.QModelIndex(), source, source, QtCore.QModelIndex(), target)
for row in self._data:
row.insert(dest, row.pop(source))
self.endMoveColumns()
def testMoveColumn():
sel = table.selectionModel()
sel.select(model.index(0, 2),
QtCore.QItemSelectionModel.Select|QtCore.QItemSelectionModel.Columns)
QtCore.QTimer.singleShot(1000, lambda: model.moveColumn(2, 0))
import sys
app = QtWidgets.QApplication(sys.argv)
test = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(test)
table = QtWidgets.QTableView()
layout.addWidget(table)
model = Model()
table.setModel(model)
b = QtWidgets.QPushButton('Push 3rd column to 1st')
layout.addWidget(b)
b.clicked.connect(testMoveColumn)
test.show()
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment