如何使 QAbstractTableModel 的数据可检查 [英] How to make QAbstractTableModel 's data checkable
本文介绍了如何使 QAbstractTableModel 的数据可检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使 QAbstractTableModel 的数据可检查
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 ?
根据 Qt 文档:Qt::CheckStateRole 并设置 Qt::ItemIsUserCheckable 可能会被使用,所以任何人都可以提供一个小例子?
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_())
推荐答案
覆盖 MyModel 中的标志函数.
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.
然后覆盖数据函数.
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
最后,你需要实现 setData 函数.
Finally, you need to implement the setData function.
def setData(self, index, value, role = Qt.EditRole):
if (role==Qt.CheckStateRole):
# Modify your data.
这篇关于如何使 QAbstractTableModel 的数据可检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文