[英]How to bold the selected text in QTextEditor in pyqt5
我有一个问题,这个问题是我无法将当前选定的文本设为粗体。 我选择了部分文本,当我尝试将当前选定的文本加粗时。 我把那部分的所有文字都加粗了。 那么问题出在哪里呢?
简而言之。 我想把“爱”这个词加粗
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.uic import loadUiType
import sip
class Widget(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(500, 500, 700, 700)
self.te = QTextEdit(self)
self.te.setText('sad man loves sad women')
self.button = QPushButton("bold the text", self)
self.button.move(150, 200)
self.button.clicked.connect(self.bold_text)
self.document = self.te.document()
self.cursor = QTextCursor(self.document)
def bold_text(self):
# bold the text
self.cursor.movePosition(QTextCursor.Start)
self.cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor)
self.format = QTextCharFormat()
self.format.setFontWeight(QFont.Bold)
self.cursor.mergeCharFormat(self.format)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
你将光标移动到Start
的文件,然后到EndOfLine
。 所以你在完整的第一行设置了粗体格式,完全忽略了选择。
如果您想将当前选择加粗,绝对不需要使用 QTextDocument 或 QTextCursor ,因为 QTextEdit 已经提供了setFontWeight()
:
def bold_text(self):
self.te.setFontWeight(QFont.Bold)
请注意,您不应使用对文本光标或文档的持久引用:虽然它在您的简单情况下有效,但光标或文档都可能发生变化,因此您应该始终动态访问它们。 此外,您可以使用 QTextEdit 的textCursor()
直接访问文本光标。
不相关,但仍然很重要:避免使用固定的几何图形,而总是更喜欢布局管理器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.