PyQt使用用户定义的小部件委派

时间:2017-09-14 14:43:40

标签: qt delegates pyqt treeview

我试图在TreeView中实现委托。代表应包含LineEdit和Button:

class Ui_Data_Delegate(QWidget):

    def __init__(self, *args, **kwargs):
        super(Ui_Data_Delegate, self).__init__(*args, **kwargs)
        self.setGeometry(QRect(10, 10, 271, 61))
        self.horizontalLayout = QHBoxLayout(self)
        self.lineEdit = QLineEdit(self)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        self.ToolButton = QToolButton(self)
        self.ToolButton.setObjectName("ToolButton")
        self.horizontalLayout.addWidget(self.ToolButton)

在createEditor函数中,我调用Ui_Data_Delegate类:

def createEditor(self, parent, option, index):

    if type == UDF.DT_ResultsSelector:

        editor = Ui_Data_Delegate(parent)
        editor.ToolButton.released.connect(self.make_selection)
        return editor
    else:
        return QStyledItemDelegate.createEditor(self, parent, option, index)

但是后来我在树视图中看不到任何编辑器: enter image description here

如果我错过了父参数:

def createEditor(self, parent, option, index):

    if type == UDF.DT_ResultsSelector:

        editor = Ui_Data_Delegate()
        editor.ToolButton.released.connect(self.make_selection)
        return editor
    else:
        return QStyledItemDelegate.createEditor(self, parent, option, index)

我明白了:

enter image description here

这几乎是正确的,但小部件应该出现在Treeview Cell中!

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我找到了答案。内容边距未设置。 因此,使用此代码可以:

class Ui_Data_Delegate(QWidget):

    def __init__(self, *args, **kwargs):
        super(Ui_Data_Delegate, self).__init__(*args, **kwargs)        
        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.lineEdit = QLineEdit(self)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        self.ToolButton = QToolButton(self)
        self.ToolButton.setObjectName("ToolButton")
        self.horizontalLayout.addWidget(self.ToolButton)