如何在 QTextEdit 中插入和清除占位符 [英] How to insert and clear placeholder in QTextEdit

查看:40
本文介绍了如何在 QTextEdit 中插入和清除占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一个带有 setText() 的 QTextEdit,但我希望在用户选择编辑文本"时清除占位符.此处显示的插图

I have a QTextEdit with setText() already but I want a the placeholder to clear when user selects the Edit Text. Illustration shown here

推荐答案

placeholderText 属性仅在 Qt 5.2 中存在,所以我为 PyQt4 实现了相同的逻辑:

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_())

这篇关于如何在 QTextEdit 中插入和清除占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆