You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QComboBox作为QTableView项委托时显示位置异常的解决求助

QComboBox作为QTableView项委托时显示异常的解决方法

问题现象

使用QComboBox作为QTableView的项委托时,编辑器的选择功能、模型数据交互均正常,但点击单元格进入编辑状态时,QComboBox并未显示在单元格内部,而是出现在主GUI外部(如截图左上角位置)。同一表格中的Freq/Qty列使用QSpinBox作为编辑器时,双击编辑能正常显示在单元格内。

问题代码

...
hb = QTableView()
hbm = HierBlocksDataModel()
hb.setModel(hbm)
hb.verticalHeader().setDefaultSectionSize(25)
lbd = LibraryBoxDelegate(hb)
hb.setItemDelegateForColumn(3, lbd)
...

class LibraryBoxDelegate(QStyledItemDelegate):
    def __init__(self, parent, node=None):
        super(LibraryBoxDelegate, self).__init__(parent)
        self.node = node

    def createEditor(self, parent, option, index):
        if self.node is not None:
            cb = QComboBox()  # 问题所在:未指定父控件
            cb.addItems(list('abc'))
            return cb

    def setEditorData(self, editor, index):
        editor.setCurrentText(index.model().data(index, Qt.DisplayRole))

    def setModelData(self, editor, model, index):
        model.setData(index, editor.currentText(), Qt.EditRole)

解决方案

问题根源在于创建QComboBox时未指定父控件。createEditor方法的parent参数是QTableView为编辑器提供的单元格容器控件,只有将编辑器的父对象设置为该参数,编辑器才会被约束在单元格区域内显示。

修改createEditor方法中的QComboBox创建代码,将parent传入:

def createEditor(self, parent, option, index):
    if self.node is not None:
        cb = QComboBox(parent)  # 传入parent参数
        cb.addItems(list('abc'))
        return cb

修改后,QComboBox会正确显示在目标单元格内,和QSpinBox的表现一致。

内容的提问来源于stack exchange,提问作者user4979733

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:10:38