How to make QAbstractTableModel 's data checkable

…衆ロ難τιáo~ 提交于 2019-12-08 01:57:07

问题


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_())

回答1:


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.


来源:https://stackoverflow.com/questions/16121537/how-to-make-qabstracttablemodel-s-data-checkable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!