如何防止QTextCursor将新插入的文本格式化为QPlainTextEdit

时间:2020-02-16 17:09:32

标签: python pyqt pyqt5 qplaintextedit qtextcursor

我正在为一种一直在使用的简单编程语言创建IDE,由于QSyntaxHighlighter类,我添加了语法突出显示,现在我想为无效代码添加自定义格式。

这是我使用QTextCursor格式化有问题的代码部分的方式

def error(self, ix, length):
    cursor = self.editor.textCursor()  # editor is a QPlainTextEdit
    cursor.setPosition(ix, QTextCursor.MoveAnchor)  # set cursor position at the beginning of the error
    cursor.movePosition(QTextCursor.Right,  # and move it the specified length, while selecting the text
                        QTextCursor.KeepAnchor,
                        length)
    cursor.setCharFormat(self.error_format)  # error_format is a QTextCharFormat

这完全符合预期,如下所示。 sort是有效的关键字,如QSyntaxHighlighter设置的粗体所示。

IDE showing a correct keyword and a mistake

问题在于,error_format现在已应用于在QPlainTextEdit中键入的任何新文本。

error_format being propagated to new text

除了被QSyntaxHighlighter所应用的格式所迷惑,如下所示,该文本仍带有下划线,因为它是一个错误,即使现在已将其注释掉,并且代码是有效的。我没有过多研究第二个问题,因为我想一定有一种方法可以重置光标所应用的所有格式,我希望通过解决第一个问题,第二个问题将变得更加清晰。

Hybrid between comment and error formatting

我正在使用PyQt5。如果不清楚,请告诉我。谢谢。

编辑:问题似乎是QTextEdit在插入新文本时采用了最后一个字符的格式,如果我这样做的话,突出显示的错误不会影响文本的结尾,就像这样

enter image description here

我可以在底部添加默认格式的新文本。

EDIT2:通过发现可以直接在文本编辑中直接设置当前char格式,我已部分解决了该问题,因此我可以执行以下操作:

old_format = cursor.charFormat()
cursor.setCharFormat(self.error_format)
self.editor.setCurrentCharFormat(old_format)

现在我只需要发现QSyntaxHighlighter再次通过时如何重置格式。

EDIT3:我已经为我的特定目的确定了解决方案,我不会回答这个问题,因为它实际上不是我提出的问题的答案,而是一种解决方法。

这就是我所做的

# Override
def keyPressEvent(self, event):
    QPlainTextEdit.keyPressEvent(self, event)
    cursor = self.textCursor()
    cursor.select(QTextCursor.Document)
    cursor.setCharFormat(self.default_format)
    cursor.clearSelection()
    self.keyPressed.emit(event)

当用户输入新内容时,只需删除光标所应用的所有格式,这对我有用,因为一旦用户执行代码,便会再次检查语法。

0 个答案:

没有答案