Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placeholder text not showing (pyside/pyqt)

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.

like image 431
eric Avatar asked Jun 17 '14 22:06

eric


1 Answers

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.

like image 171
mata Avatar answered Oct 02 '22 03:10

mata