我想设置一个 QTextEdit
的占位文本。我知道如何为 QLineEdit
设置它,有一个属性 setPlaceHolderText
。但是这个属性对于 QTextEdit
不可用。请提供您宝贵的建议来解决这个问题。
QTextCursor textCursor;
textCursor.setPosistion(0, QTextCursor::MoveAnchor);
textedit->setTextCursor( textCursor );
\n
换行。QtWidgets
重新映射回QtGui
。class QPlainTextEdit(QtWidgets.QPlainTextEdit):
"""QPlainTextEdit with placeholder text option.
Reimplemented from the C++ code used in Qt5.
"""
def __init__(self, *args, **kwargs):
super(QPlainTextEdit, self).__init__(*args, **kwargs)
self._placeholderText = ''
self._placeholderVisible = False
self.textChanged.connect(self.placeholderVisible)
def placeholderVisible(self):
"""Return if the placeholder text is visible, and force update if required."""
placeholderCurrentlyVisible = self._placeholderVisible
self._placeholderVisible = self._placeholderText and self.document().isEmpty() and not self.hasFocus()
if self._placeholderVisible != placeholderCurrentlyVisible:
self.viewport().update()
return self._placeholderVisible
def placeholderText(self):
"""Return text used as a placeholder."""
return self._placeholderText
def setPlaceholderText(self, text):
"""Set text to use as a placeholder."""
self._placeholderText = text
if self.document().isEmpty():
self.viewport().update()
def paintEvent(self, event):
"""Override the paint event to add the placeholder text."""
if self.placeholderVisible():
painter = QtGui.QPainter(self.viewport())
colour = self.palette().text().color()
colour.setAlpha(128)
painter.setPen(colour)
painter.setClipRect(self.rect())
margin = self.document().documentMargin()
textRect = self.viewport().rect().adjusted(margin, margin, 0, 0)
painter.drawText(textRect, QtCore.Qt.AlignTop | QtCore.Qt.TextWordWrap, self.placeholderText())
super(QPlainTextEdit, self).paintEvent(event)
not self.hasFocus()
部分即可。Rafe
的答案,但它并不太好用,所以我向下滚动,看到了这个,真的很高兴有人花时间改进它。我试图点赞,结果发现这是我的答案。 - Peterclass PlainTextEditWithPlaceholderText(QtGui.QPlainTextEdit):
def __init__(self, parent=None):
super(PlainTextEditWithPlaceholderText, self).__init__(parent)
self.placeholderText = "" # Qt-style camelCase
def setPlaceholderText(self, text):
self.placeholderText = text
def paintEvent(self, _event):
"""
Implements the same behavior as QLineEdit's setPlaceholderText()
Draw the placeholder text when there is no text entered and the widget
doesn't have focus.
"""
if self.placeholderText and not self.hasFocus() and not self.toPlainText():
painter = QtGui.QPainter(self.viewport())
color = self.palette().text().color()
color.setAlpha(128)
painter.setPen(color)
painter.drawText(self.geometry().topLeft(), self.placeholderText)
else:
super(PlainTextEditWithPlaceholderText, self).paintEvent(event)
self.viewport().update()
并稍微调整文本的位置,但除此之外一切都很好!谢谢! - meepzh