PyQt5中如何实现QTextEdit控件内每一行文本全部居中显示
原因说明
QTextEdit.setAlignment()方法仅对当前选中的文本或后续新输入的文本生效,你先调用setPlainText()插入文本再设置对齐,对齐规则不会作用到已插入的已有内容上,因此无法实现每行居中。
可行解决方案
方案1:插入文本后全选应用对齐(最简便)
from PyQt5.QtCore import Qt self.descriptionText.setPlainText("First Line\nSecond Line\nThird Line") # 全选所有已插入的文本 self.descriptionText.selectAll() # 给选中内容应用居中对齐 self.descriptionText.setAlignment(Qt.AlignCenter) # 可选:清除选中状态,避免文本全被高亮 self.descriptionText.textCursor().clearSelection()
方案2:统一设置文本块格式(永久生效,后续输入默认居中)
如果需要后续新增的所有文本默认都居中,可以遍历文档块统一设置格式:
from PyQt5.QtCore import Qt from PyQt5.QtGui import QTextBlockFormat, QTextCursor self.descriptionText.setPlainText("First Line\nSecond Line\nThird Line") doc = self.descriptionText.document() block_format = QTextBlockFormat() block_format.setAlignment(Qt.AlignCenter) # 遍历所有文本块应用对齐格式 cursor = QTextCursor(doc) cursor.beginEditBlock() while not cursor.atEnd(): cursor.setBlockFormat(block_format) cursor.movePosition(QTextCursor.NextBlock) cursor.endEditBlock()
内容的提问来源于stack exchange,提问作者ProtossManse
相关产品推荐
相关产品推荐

