gpt4 book ai didi

qt - 如何使 QAbstractTableModel 的数据可检查

转载 作者:行者123 更新时间:2023-12-05 01:48:13 24 4
gpt4 key购买 nike

如何使 QAbstractTableModel 的数据可检查

我想让下面代码中的每个单元格都可以被用户选中或取消选中,如何修改代码?

根据Qt文档:Qt::CheckStateRole和设置Qt::ItemIsUserCheckable可能会用到,所以谁能给个小例子?

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 中的标志函数。

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

这表示您的模型中的索引是可检查的。

然后覆盖数据函数。

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函数。

def setData(self, index, value, role = Qt.EditRole):
if (role==Qt.CheckStateRole):
# Modify your data.

关于qt - 如何使 QAbstractTableModel 的数据可检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16121537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com