Reputation: 2058
I know you can set the alignment of the text using setAlignment()
, but that has no effect on the placeholder text. Maybe you would need to edit the styleSheet
of the underlying document
in order to do it? Or is the document only relevant for the actual text but not the placeholder?
Here's an MWE to play around with:
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_())
Upvotes: 1
Views: 1555
Reputation: 48231
The placeholder cannot be directly customized, as it is directly painted by the QTextEdit using the default top alignment, so the only solution is to subclass, overwrite the paintEvent and paint the placeholder using your own alignment.
You might also add much more control by using a QTextDocument, which will allow you to use html and custom colors/alignment/etc.
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>'
)
# ...
Upvotes: 1