我在QAbstractTableModel中使用自己的表模型,其中我有第一个带复选框的col(可检查原因标志Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
)。我在尝试使用复选框时遇到麻烦,因为它们在显示的表格中无法检查(无法在them中进行检查或取消选中)。
我做错了什么?我在自己的表模型类中使用此方法:
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
答案 0 :(得分:1)
你必须为它存储状态,我们需要永久作为参考,为此我们使用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_())