Placeholder text not showing (pyside/pyqt)

醉酒当歌 提交于 2019-12-01 16:10:33

问题


Learning PySide, I'm tweaking a text edit widget (QLineEdit) and trying to set the placeholder text using setPlaceHolderText as in the code snippet below (which I invoke from main). Unfortunately, it is not working as I expected. The code runs, but the text box is blank, does not show the placeholder text. I am in Windows 7, Python 2.7 (working in 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()        

Anyone understand what I'm doing wrong? I'm following examples from the following sites:

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

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

And don't see what I'm doing differently.


回答1:


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.



来源:https://stackoverflow.com/questions/24274318/placeholder-text-not-showing-pyside-pyqt

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