gpt4 book ai didi

Qt QTableView如何有一个只有复选框的列

转载 作者:行者123 更新时间:2023-12-03 14:42:46 25 4
gpt4 key购买 nike

我们正在使用 QTableView使用 Qt 4.6.3,并且需要一个在每个单元格中只有一个复选框的列。我们正在使用 QAbstractTableModel 的自定义子类作为 QTableView 的模型.现在,我们有一个复选框,通过设置 Qt::ItemIsUserCheckable旗帜。但是我们无法弄清楚如何摆脱复选框旁边的空白文本框!

怎么做专栏仅限 有一个复选框,没有别的?

最佳答案

注意:Dave 的答案也适用于使用 PySide 或 PyQt4 的 Python。我翻译了,效果很好。此外,我添加了复选框不接受用户输入并在单元格不可编辑时显示为只读状态的功能。
感谢戴夫的代码!

class CheckBoxDelegate(QStyledItemDelegate):

def createEditor(self, parent, option, index):
'''
Important, otherwise an editor is created if the user clicks in this cell.
'''
return None

def paint(self, painter, option, index):
'''
Paint a checkbox without the label.
'''
checked = bool(index.model().data(index, Qt.DisplayRole))
check_box_style_option = QStyleOptionButton()

if (index.flags() & Qt.ItemIsEditable) > 0:
check_box_style_option.state |= QStyle.State_Enabled
else:
check_box_style_option.state |= QStyle.State_ReadOnly

if checked:
check_box_style_option.state |= QStyle.State_On
else:
check_box_style_option.state |= QStyle.State_Off

check_box_style_option.rect = self.getCheckBoxRect(option)
if not index.model().hasFlag(index, Qt.ItemIsEditable):
check_box_style_option.state |= QStyle.State_ReadOnly

QApplication.style().drawControl(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.
'''
if not (index.flags() & Qt.ItemIsEditable) > 0:
return False

# Do not change the checkbox-state
if event.type() == QEvent.MouseButtonRelease or event.type() == QEvent.MouseButtonDblClick:
if event.button() != Qt.LeftButton or not self.getCheckBoxRect(option).contains(event.pos()):
return False
if event.type() == QEvent.MouseButtonDblClick:
return True
elif event.type() == QEvent.KeyPress:
if event.key() != Qt.Key_Space and event.key() != Qt.Key_Select:
return False
else:
return False

# Change the checkbox-state
self.setModelData(None, model, index)
return True

def setModelData (self, editor, model, index):
'''
The user wanted to change the old state in the opposite.
'''
newValue = not bool(index.model().data(index, Qt.DisplayRole))
model.setData(index, newValue, Qt.EditRole)


def getCheckBoxRect(self, option):
check_box_style_option = QStyleOptionButton()
check_box_rect = QApplication.style().subElementRect(QStyle.SE_CheckBoxIndicator, check_box_style_option, None)
check_box_point = QPoint (option.rect.x() +
option.rect.width() / 2 -
check_box_rect.width() / 2,
option.rect.y() +
option.rect.height() / 2 -
check_box_rect.height() / 2)
return QRect(check_box_point, check_box_rect.size())

关于Qt QTableView如何有一个只有复选框的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3363190/

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