Placeholder text not showing (pyside/pyqt)

走远了吗. 提交于 2019-12-01 18:00:57

As your widget only contains only one component (the QLineEdit), that component will always grab the focus initially. The placeholder text is only shown if the edit is empty and does not have the focus*.

A simple solution would be to focus a different component befor showing your widget, e.g. by inserting self.setFocus() before self.show().
The downside is that this way the user has to click into the text field or press Tab before being able to write into the field. To avoid that, you can intercept the keyPress event on the widget.

Example:

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)

*Note: This has changed in Qt5 where the paceholder text is shown as long as the line edit is empty. Unfortunately PySide doesn't support Qt5 (yet), so you'd have to use PyQt5.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!