【问题标题】:Placeholder text not showing (pyside/pyqt)占位符文本未显示(pyside/pyqt)
【发布时间】:2014-08-08 02:03:50
【问题描述】:

学习 PySide,我正在调整文本编辑小部件 (QLineEdit) 并尝试使用 setPlaceHolderText 设置占位符文本,如下面的代码 sn-p 所示(我从 main 调用)。不幸的是,它没有按我的预期工作。代码运行,但文本框为空白,不显示占位符文本。我在 Windows 7,Python 2.7(在 iPython 中工作)。

class MyTextEdit(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.textEditor=QtGui.QLineEdit(self) 
        self.textEditor.move(50,15)
        self.textEditor.setPlaceholderText("Don't mind me.") 
        self.setGeometry(100, 100, 200, 50)
        self.show()        

有人明白我做错了什么吗?我正在关注以下网站的示例:

http://nullege.com/codes/search/PyQt4.QtGui.QLineEdit.setPlaceholderText

http://www.pythoncentral.io/pyside-pyqt-tutorial-interactive-widgets-and-layout-containers/

而且看不出我在做什么不同。

【问题讨论】:

    标签: python qt user-interface pyqt pyside


    【解决方案1】:

    由于您的小部件仅包含一个组件(QLineEdit),因此该组件最初总是会获取焦点。如果编辑为空且没有具有焦点*,则占位符文本为only shown

    一个简单的解决方案是在显示您的小部件之前聚焦不同的组件,例如 通过在self.show() 之前插入self.setFocus()
    缺点是这种方式用户必须单击文本字段或按 Tab 才能写入该字段。为避免这种情况,您可以拦截小部件上的keyPress 事件。

    例子:

    class MyTextEdit(QtGui.QWidget):
        '''Some positioning'''
        def __init__(self):
            QtGui.QWidget.__init__(self)
            self.textEditor=QtGui.QLineEdit(self) 
            self.textEditor.move(50,15)
            self.textEditor.setPlaceholderText("Hi I'm de fault.") 
            self.setGeometry(100, 100, 200, 50)
            self.setFocus()
            self.show()
    
        def keyPressEvent(self, evt):
            self.textEditor.setFocus()
            self.textEditor.keyPressEvent(evt)
    

    *注意:这在Qt5 中有所改变,只要行编辑为空,就会显示起搏器文本。不幸的是 PySide 还不支持 Qt5,所以你必须使用 PyQt5。

    【讨论】:

    • 非常感谢您提供清晰而有帮助的回复。
    • 如何为占位符文本设置特定颜色
    • 嗯,不是那么容易,如果有一个样式表sub-control 会很好,但是没有。 this 之类的东西应该可以工作,使用事件过滤器根据需要更改组件的样式表。
    猜你喜欢
    • 2021-11-02
    • 2021-03-04
    • 1970-01-01
    • 2023-02-15
    • 2011-06-02
    • 2016-09-14
    • 2023-01-26
    • 2018-08-08
    • 1970-01-01
    相关资源
    最近更新 更多