有没有办法只更改 QTextEdit 中的部分文本?

Is there a way to only change a part of the text in QTextEdit?

我只想更改文本的一部分,基本上我想要这样,如果用户输入错误,我的程序会自动更正它。现在我的代码只是重置整个文本以更改拼写错误。

这是我的代码

class MainEditor(QtWidgets.QTextEdit):
    def __init__(self):
        super().__init__()
        self.textChanged.connect(self.current_text)
        self.just_changed = False

    def current_text(self):
        if not self.just_changed:
            whole = self.toPlainText()
            whole = whole.split(' ')
            if len(whole) >= 2:
                last_word = whole[-2]
                # here was some logic I am just taking it as stop and assuming it was typo 
                correct_word = "stop"
                whole[-2] = correct_word
                self.just_changed = True
                self.setText(' '.join(whole))
        else:
            self.just_changed = False

如您所见,它会再次重新输入整个文本以修复一个拼写错误,有没有办法只更改 PySide6 中的部分文本?

附加信息

然后将这个 class 对象添加到 QVBoxLayout,然后将 QVBoxLayout 添加到主 QVBoxLayout,然后将其添加到 QtWidgets.QWidget,我还使用 setHtml 功能将其更改为加粗。

你必须使用QTextCursor来进行修改,在下面的演示中,如果用户写了“tops”、“sstop”、“stoop”中的任何一个,那么它将被更正为“stop”

import re

from PySide6 import QtWidgets, QtGui


class MainEditor(QtWidgets.QTextEdit):
    WORD_REGEX = re.compile(
        r"\b[^\d\W]+\b"
    )  # 

    def __init__(self):
        super().__init__()
        self.textChanged.connect(self.current_text)

    def current_text(self):
        position = 0
        text = self.toPlainText()
        res = self.WORD_REGEX.search(text[position:])
        while res:
            word = res.group()
            correct_word = self.fix_word(word)
            position += res.start()
            if correct_word:
                self.replace_word(position, word, correct_word)
                position += len(correct_word)
            else:
                position += len(word)
            text = self.toPlainText()
            res = self.WORD_REGEX.search(text[position:])

    def replace_word(self, start, word, new_word):
        cursor = QtGui.QTextCursor(self.document())
        cursor.setPosition(start)
        cursor.movePosition(
            QtGui.QTextCursor.MoveOperation.Right,
            QtGui.QTextCursor.MoveMode.KeepAnchor,
            len(word),
        )
        cursor.deleteChar()
        cursor.insertText(new_word)

    def fix_word(self, word):
        if word in ("tops", "sstop", "stoop"):
            return "stop"


def main():
    app = QtWidgets.QApplication()

    w = MainEditor()
    w.show()

    app.exec()


if __name__ == "__main__":
    main()