我正在使用 Pandas dataframe 动态创建 QTableView。我有示例代码在这里。
我可以创建表格,并显示复选框,但我无法让复选框反映模型数据,甚至无法将其更改为未选中状态。
我正在按照之前这个问题的示例代码,以@raorao的答案为指南。这将在表格中显示框,但没有任何功能正常工作。
有人可以建议做出任何更改,或者这段代码有什么问题。为什么它不能反映模型,为什么它不能更改?
请查看我的完整示例代码在这里。 编辑一:在Frodon的评论后进行更新:用比较xxx == 'True'来更正字符串转换为bool。
我正在按照之前这个问题的示例代码,以@raorao的答案为指南。这将在表格中显示框,但没有任何功能正常工作。
有人可以建议做出任何更改,或者这段代码有什么问题。为什么它不能反映模型,为什么它不能更改?
请查看我的完整示例代码在这里。 编辑一:在Frodon的评论后进行更新:用比较xxx == 'True'来更正字符串转换为bool。
class CheckBoxDelegate(QtGui.QStyledItemDelegate):
"""
A delegate that places a fully functioning QCheckBox in every
cell of the column to which it's applied
"""
def __init__(self, parent):
QtGui.QItemDelegate.__init__(self, parent)
def createEditor(self, parent, option, index):
'''
Important, otherwise an editor is created if the user clicks in this cell.
** Need to hook up a signal to the model
'''
return None
def paint(self, painter, option, index):
'''
Paint a checkbox without the label.
'''
checked = index.model().data(index, QtCore.Qt.DisplayRole) == 'True'
check_box_style_option = QtGui.QStyleOptionButton()
if (index.flags() & QtCore.Qt.ItemIsEditable) > 0:
check_box_style_option.state |= QtGui.QStyle.State_Enabled
else:
check_box_style_option.state |= QtGui.QStyle.State_ReadOnly
if checked:
check_box_style_option.state |= QtGui.QStyle.State_On
else:
check_box_style_option.state |= QtGui.QStyle.State_Off
check_box_style_option.rect = self.getCheckBoxRect(option)
# this will not run - hasFlag does not exist
#if not index.model().hasFlag(index, QtCore.Qt.ItemIsEditable):
#check_box_style_option.state |= QtGui.QStyle.State_ReadOnly
check_box_style_option.state |= QtGui.QStyle.State_Enabled
QtGui.QApplication.style().drawControl(QtGui.QStyle.CE_CheckBox, check_box_style_option, painter)
def editorEvent(self, event, model, option, index):
'''
Change the data in the model and the state of the checkbox
if the user presses the left mousebutton or presses
Key_Space or Key_Select and this cell is editable. Otherwise do nothing.
'''
print 'Check Box editor Event detected : '
if not (index.flags() & QtCore.Qt.ItemIsEditable) > 0:
return False
print 'Check Box edior Event detected : passed first check'
# Do not change the checkbox-state
if event.type() == QtCore.QEvent.MouseButtonRelease or event.type() == QtCore.QEvent.MouseButtonDblClick:
if event.button() != QtCore.Qt.LeftButton or not self.getCheckBoxRect(option).contains(event.pos()):
return False
if event.type() == QtCore.QEvent.MouseButtonDblClick:
return True
elif event.type() == QtCore.QEvent.KeyPress:
if event.key() != QtCore.Qt.Key_Space and event.key() != QtCore.Qt.Key_Select:
return False
else:
return False
# Change the checkbox-state
self.setModelData(None, model, index)
return True
checked = bool(index.model().data(index, QtCore.Qt.DisplayRole))
确实返回布尔类型吗?我本来会写成checked = index.model().data(index, QtCore.Qt.DisplayRole).toBool()
的,因为 data() 的结果是 QVariant 类型的。 - Frodon