我知道您可以使用setAlignment()
设置文本的对齐方式,但这对占位符文本没有影响。也许您需要编辑基础styleSheet
的document
来执行此操作?还是文档仅与实际文本相关,而与占位符无关?
这里是一个MWE可以玩:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QApplication, QGridLayout, QTextEdit
class Test(QDialog):
def __init__(self):
super().__init__()
self.edit = QTextEdit()
self.edit.setPlaceholderText(
# '<html><body><p align="center">'
'this is a placeholder'
# '</p></body></html>'
)
self.edit.setAlignment(Qt.AlignHCenter)
self.lay = QGridLayout(self)
self.lay.addWidget(self.edit)
self.setLayout(self.lay)
if __name__ == '__main__':
app = QApplication(sys.argv)
GUI = Test()
GUI.show()
sys.exit(app.exec_())
无法直接自定义占位符,因为它是由QTextEdit使用默认的顶部对齐方式直接绘制的,所以唯一的解决方案是子类化,覆盖paintEvent并使用自己的对齐方式绘制占位符。
您还可以通过使用QTextDocument添加更多控制,这将允许您使用html和自定义颜色/对齐方式等。>>
class HtmlPlaceholderTextEdit(QTextEdit):
_placeholderText = ''
def setPlaceholderText(self, text):
if Qt.mightBeRichText(text):
self._placeholderText = QTextDocument()
try:
color = self.palette().placeholderText().color()
except:
# for Qt < 5.12
color = self.palette().windowText().color()
color.setAlpha(128)
# IMPORTANT: the default stylesheet _MUST_ be set *before*
# adding any text, otherwise it won't be used.
self._placeholderText.setDefaultStyleSheet(
'''body {{color: rgba({}, {}, {}, {});}}
'''.format(*color.getRgb()))
self._placeholderText.setHtml(text)
else:
self._placeholderText = text
self.update()
def placeholderText(self):
return self._placeholderText
def paintEvent(self, event):
super().paintEvent(event)
if self.document().isEmpty() and self.placeholderText():
qp = QPainter(self.viewport())
margin = self.document().documentMargin()
r = QRectF(self.viewport().rect()).adjusted(margin, margin, -margin, -margin)
text = self.placeholderText()
if isinstance(text, str):
try:
color = self.palette().placeholderText().color()
except:
# for Qt < 5.12
color = self.palette().windowText().color()
color.setAlpha(128)
qp.setPen(color)
qp.drawText(r, self.alignment() | Qt.TextWordWrap, text)
else:
text.setPageSize(self.document().pageSize())
text.drawContents(qp, r)
class Test(QDialog):
def __init__(self):
super().__init__()
self.edit = HtmlPlaceholderTextEdit()
self.edit.setPlaceholderText(
'<html><body><p align="center">'
'this is a <font color="blue">placeholder</font>'
'</p></body></html>'
)
# ...