我正在开发一个使用 PyQt 的项目,并且我对 QTableView 及其项目编辑器有疑问。我的 TableModel 有 2 列,其中的数据紧密耦合并且必须同时更改。 我已经使用 QComboBox 继承的编辑器重新实现了 QStyledItemDelegate 类。这一切都很完美。 但我需要我的编辑器打开两栏。我发现的所有示例仅在用户单击的一个单元格上打开编辑器。示例使用重新实现的 updateEditorGeometry 方法根据选项参数更新几何图形。是否可以在 updateEditorGeometry 方法中获取相邻列的宽度来计算两个列的总宽度并更新其基础上的编辑器(组合框)几何图形?
我当前(最小)基于 QStyledItemDelegate 的类:
class ComboBoxDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super(SpinBoxDelegate, self).__init__(parent)
def createEditor(self, parent, option, index):
editor = QComboBox(parent)
return editor
def setEditorData(self, editor, index):
pass
def setModelData(self, editor, model, index):
pass
def updateEditorGeometry(self, editor, option, index):
row = index.row()
column = index.column()
if column == 1:
neighbourIndex = index.model().index(row, 0, QModelIndex())
editor.setGeometry(option.rect)
@ekhumoro 评论是关键! 这里 updateEditorGeometry() 代码片段
def updateEditorGeometry(self, editor, option, index):
row = index.row()
column = index.column()
if column == 1:
neighbourIndex = index.model().index(row, 0, QModelIndex())
neighbourRect = self.parent().visualRect(neighbourIndex)
width = option.rect.width() + neighbourRect.width()
newRect = QRect(option.rect)
newRect.setWidth(width)
newRect.moveLeft(0)
editor.setGeometry(newRect)
View 必须是 delegate 的父级