I have a QTextEdit with setText() already but I want a the placeholder to clear when user selects the Edit Text. Illustration shown here
Asked
Active
Viewed 1,462 times
1
-
Check this doc, https://doc.qt.io/qt-5/qtextedit.html#placeholderText-prop – Konstantin Jul 10 '19 at 08:51
-
@Konstantin That property is available from Qt 5.2 which is equivalent to PyQt5 5.2 but not for PyQt4, so it does not help much in this case – eyllanesc Jul 10 '19 at 09:06
-
Possible duplicate of [How to set the PlaceHolderText for QTextEdit](https://stackoverflow.com/questions/13348117/how-to-set-the-placeholdertext-for-qtextedit) – Dimitry Ernot Jul 10 '19 at 09:23
-
Thanks. For this I noted the missing implementation in PyQt4 as is for only TextEdit – Hempire Jul 10 '19 at 09:26
1 Answers
1
The placeholderText property only exists from Qt 5.2 so I have implemented the same logic for PyQt4:
from PyQt4 import QtCore, QtGui
class TextEdit(QtGui.QTextEdit):
@property
def placeholderText(self):
if not hasattr(self, "_placeholderText"):
self._placeholderText = ""
return self._placeholderText
@placeholderText.setter
def placeholderText(self, text):
self._placeholderText = text
self.update()
def isPreediting(self):
lay = self.textCursor().block().layout()
if lay and lay.preeditAreaText():
return True
return False
def paintEvent(self, event):
super(TextEdit, self).paintEvent(event)
if (
self.placeholderText
and self.document().isEmpty()
and not self.isPreediting()
):
painter = QtGui.QPainter(self.viewport())
col = self.palette().text().color()
col.setAlpha(128)
painter.setPen(col)
margin = int(self.document().documentMargin())
painter.drawText(
self.viewport().rect().adjusted(margin, margin, -margin, -margin),
QtCore.Qt.AlignTop | QtCore.Qt.TextWordWrap,
self.placeholderText,
)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
te = TextEdit()
te.placeholderText = "Stack Overflow"
w = QtGui.QWidget()
lay = QtGui.QVBoxLayout(w)
lay.addWidget(QtGui.QLineEdit())
lay.addWidget(te)
w.show()
sys.exit(app.exec_())

eyllanesc
- 235,170
- 19
- 170
- 241
-
-
-
Here is the generated code https://codeshare.io/GAzLbr and here is the UI code https://codeshare.io/GqEb7Z – Hempire Jul 10 '19 at 10:47