[PyQt] QTableView cell deselected after soting

Sebastian Elsner sebastianelsner at freenet.de
Mon Sep 2 09:57:18 BST 2013


Hello,

I have found a strange behavior with a combo of QTableView, 
QSortFilterProxyView and disabled items. If you select a row in the 
table from the example below then sort by a column, the cell in the last 
column will be deselected after sorting. This happens only for cells 
with ItemIsSelectable as it's only item flag. Is there something I can 
do about this?

Example:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

my_array = [['00', '01', '02'],
             ['10', '11', '12'],
             ['20', '21', '22']]

def main():
     app = QApplication(sys.argv)
     w = MyWindow()
     w.show()
     sys.exit(app.exec_())


class MyWindow(QWidget):
     def __init__(self, *args):
         QWidget.__init__(self, *args)

         sorttablemodel = QSortFilterProxyModel(self)
         tablemodel = MyTableModel(my_array, self)
         sorttablemodel.setSourceModel(tablemodel)
         tableview = QTableView()
         tableview.setModel(sorttablemodel)
tableview.setSelectionBehavior(QAbstractItemView.SelectRows)
         tableview.setSortingEnabled(True)
         layout = QVBoxLayout(self)
         layout.addWidget(tableview)
         self.setLayout(layout)


class MyTableModel(QAbstractTableModel):
     def __init__(self, datain, parent=None, *args):
         QAbstractTableModel.__init__(self, parent, *args)
         self.arraydata = datain

     def rowCount(self, parent):
         return len(self.arraydata)

     def columnCount(self, parent):
         return len(self.arraydata[0])

     def data(self, index, role):
         if not index.isValid():
             return QVariant()
         elif role != Qt.DisplayRole:
             return QVariant()
         return QVariant(self.arraydata[index.row()][index.column()])

     def flags(self, index):
         if index.column() == 2:
             return Qt.ItemIsSelectable
         return QAbstractTableModel.flags(self, index)

if __name__ == "__main__":
     main()

Cheers

Sebastian



More information about the PyQt mailing list