python - QLineEdit 在 setText 后不显示文本

标签 python qt pyside qlineedit qstyleditemdelegate

我被难住了。在下面的代码中:

class LineEdit(QtGui.QLineEdit):

def __init__(self, value="", parent=None, commit=None):
    super(LineEdit, self).__init__(parent=parent)
    self.setText("blabla")
    self.commit = commit
    self.editingFinished.connect(self.on_change)
    print self.text()

self.text() 是“blabla”,但 LineEdit 不显示文本,编辑后 self.text() 是“”。 编辑器是在 QStyledItemDelegate() 中创建的,带有用于 QTreeView() 的 createEditor()。

任何人都可以向我解释为什么会发生这种情况以及如何解决它吗?

最佳答案

如果您使用的是项目委托(delegate),则编辑器中显示的初始文本将从模型中获取,并且任何现有文本都将被覆盖。

要控制编辑前后发生的事情,重新实现 setEdtorDatasetModelData项目委托(delegate)的方法:

class Delegate(QtGui.QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        if index.column() < 2:
            return LineEdit(parent)
        return super(Delegate, self).createEditor(parent, option, index)

    def setEditorData(self, editor, index):
        if index.column() == 0:
            editor.setText('blabla')
        elif index.column() == 1:
            editor.setText(index.data().toString())
            # Python 3
            # editor.setText(index.data())
        else:
            super(Delegate, self).setEditorData(editor, index)

    def setModelData(self, editor, model, index):
        if index.column() < 2:
            value = editor.text()
            print(value)
            model.setData(index, value, QtCore.Qt.EditRole)
        else:
            super(Delegate, self).setModelData(editor, model, index)

关于python - QLineEdit 在 setText 后不显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27878799/

相关文章:

python - 根据行出现选择数据框结果

python - MatPlotLib:给定数据集 3,绘制 2 的图表并使用 3 作为标签

python - 无法 reshape (枢轴) Pandas DF

c++ - 如何在 Qt 中检测 Windows 事件?

python - 如何设置和使用 python 审计 Hook

c++ - 在命令行上启动服务器与在应用程序内启动服务器

c++ - 将多个参数传递给插槽

python - 在 PySide 中使用 QtHostinfo.lookupHost

drag-and-drop - 从 QTabWidget 拖放选项卡

python - 在 PySide/PyQt 中使用 drawPolyline 制作动画波