Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make QAbstractTableModel 's data checkable

Tags:

qt

pyqt

pyside

How to make QAbstractTableModel 's data checkable

I want to make each cell in the following code can be checked or unchecked by the user ,how to modify the code ?

according to the Qt documentation :Qt::CheckStateRole and set the Qt::ItemIsUserCheckable might be used ,so anyone can give a little sample ?

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

class MyModel(QAbstractTableModel):   

    def __init__(self, parent=None):   

        super(MyModel, self).__init__(parent)   

    def rowCount(self, parent = QModelIndex()):   

        return 2

    def columnCount(self,parent = QModelIndex()) :   

        return 3

    def data(self,index, role = Qt.DisplayRole) :   

        if (role == Qt.DisplayRole):   

            return "Row{}, Column{}".format(index.row() + 1, index.column() +1)   

        return None

if __name__ == '__main__':   

    app =QApplication(sys.argv)   

    tableView=QTableView()   
    myModel = MyModel (None);    
    tableView.setModel( myModel );          
    tableView.show();   
    sys.exit(app.exec_())
like image 445
iMath Avatar asked Aug 31 '25 10:08

iMath


1 Answers

Override the flags function in MyModel.

def flags(self, index)
    return super(MyModel, self).flags(index)|QtCore.Qt.ItemIsUserCheckable

This says that the index in your model is checkable.

Then override the data function.

def data(self,index, role = Qt.DisplayRole) :   
    if (role == Qt.DisplayRole):   
        return "Row{}, Column{}".format(index.row() + 1, index.column() +1)
    elif (role==Qt.CheckStateRole):
        # read from your data and return Qt.Checked or Unchecked
    return None

Finally, you need to implement the setData function.

def setData(self, index, value, role = Qt.EditRole):
    if (role==Qt.CheckStateRole):
        # Modify your data.
like image 132
Min Lin Avatar answered Sep 03 '25 02:09

Min Lin