如何在pyqt5的QTextEditor中加粗所选文本

How to bold the selected text in QTextEditor in pyqt5

我有一个问题,这个问题是我无法将当前 selected 文本设为粗体。我 select 部分文本,当我尝试将当前 selected 文本加粗时。我把那部分的所有文字都加粗了。那么问题出在哪里?

简而言之。我想把 'loves'

这个词加粗
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() 直接访问文本光标。

不相关,但仍然很重要:避免固定的几何图形,总是更喜欢 layout managers