为什么格式在单独的 QTextDocuments 之间进行,我该如何防止它?

Why is formatting carrying over between separate QTextDocuments and how can I prevent it?

我目前正在使用 QTextEdit 开发所见即所得的文本编辑器。每次加载新文件时,我都会重置并重新格式化 QTextDocument,读取文件(空白),然后 .setHtml() 将其内容提交给编辑器。我打算让每个新创建的文件始终具有在单个函数中定义的相同默认样式。

相反,输入到空文件中的新文本正在接收来自先前加载的 QTextDocument 的格式,而不是默认为我提供的格式。如果我将语法突出显示的代码复制粘贴到一个文档中,然后创建并键入一个新文档,这是最明显的。尽管其 html 结构中不存在,但字体、字体颜色和背景颜色都将转移到新文档中。


这是我目前 运行 在任何文件加载到 QTextEdit 之前的功能:

fontDefault = QFont()
fontDefault.setFamily("Yantramanav")
fontDefault.setPointSize(11)
fontDefault.setWeight(QFont.Normal)

# editor is a QTextEdit.
def reset_document(editor, defaultFont=fontDefault):
    newDocument = QTextDocument()
    newDocument.setDocumentMargin(12)
    newDocument.setDefaultFont(defaultFont)

    editor.setDocument(newDocument)
    editor.setCurrentFont(defaultFont)

    # Stored on the QTextEdit yet is reset when replacing the QTextDocument.
    editor.setTabStopWidth(33)

我原以为存储格式的文档被替换后,所有旧格式都会丢失。为什么不是这种情况,我如何确保只应用我的默认样式?

QTextCursor 在文档之间携带了之前的 charFormat。 即使它指向的 QTextDocument 被替换,光标本身仍然存在并被分配给新文档。这个过程显然不会导致光标从其当前位置采样 charFormat,就像每次移动光标时发生的那样,因此它仍然从上一个文档中的最后一个位置携带 charFormat。

防止这种重叠就像替换或移动光标一样简单,这两者都会导致光标从新文档中获取其 charFormat。将以下内容之一添加到 reset_document() 函数中:

# 1. Remove old formatting by replacing the cursor.
newCursor = QTextCursor(newDocument)
editor.setTextCursor(newCursor)
# 2. Remove old formatting by moving the cursor.
oldCursor = editor.textCursor()
oldCursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)
editor.setTextCursor(oldCursor)