我正在使用自己的表模型和QAbstractTableModel,其中我有第一个带有复选框的列(可检查的原因标志Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
(。当我尝试使用复选框时,我遇到了问题,因为它们在显示的表格中不可选中(无法选中或取消选中(。
我做错了什么?我在自己的表模型类中使用此方法:
def data(self, index, role):
row = index.row()
col = index.column()
if role == Qt.DisplayRole:
return '{0}'.format(self.tableData[row][col])
if role == Qt.CheckStateRole:
if col == 0:
return Qt.Unchecked
else:
return None
def setData(self, index, value, role):
if not index.isValid():
return False
if (role == Qt.CheckStateRole):
if (index.data(Qt.CheckStateRole) == Qt.Checked):
return True
else:
return False
else:
return False
您必须存储它的状态,我们需要有一些永久的东西作为参考,为此我们使用QPersistentModelIndex
,在本例中是一个字典,其中键是QPersistentModelIndex
,值是QCheckBox
的状态。
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class TableModel(QAbstractTableModel):
def __init__(self, parent=None):
super(TableModel, self).__init__(parent)
self.tableData = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
self.checks = {}
def columnCount(self, *args):
return 3
def rowCount(self, *args):
return 3
def checkState(self, index):
if index in self.checks.keys():
return self.checks[index]
else:
return Qt.Unchecked
def data(self, index, role=Qt.DisplayRole):
row = index.row()
col = index.column()
if role == Qt.DisplayRole:
return '{0}'.format(self.tableData[row][col])
elif role == Qt.CheckStateRole and col == 0:
return self.checkState(QPersistentModelIndex(index))
return None
def setData(self, index, value, role=Qt.EditRole):
if not index.isValid():
return False
if role == Qt.CheckStateRole:
self.checks[QPersistentModelIndex(index)] = value
return True
return False
def flags(self, index):
fl = QAbstractTableModel.flags(self, index)
if index.column() == 0:
fl |= Qt.ItemIsEditable | Qt.ItemIsUserCheckable
return fl
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
view = QTableView()
model = TableModel()
view.setModel(model)
view.show()
sys.exit(app.exec_())