为什么格式化会在单独的QTextDocuments之间进行,如何防止呢?

问题描述

我目前正在使用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)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...