语法高亮显示无法在QMainWindow中工作



我正在尝试使用PyQt4实现语法高亮显示。我尝试过的例子工作得很好,但一旦我将其应用到应用程序中,高亮显示就停止了。

我创建了一个最小的例子来重现下面的问题。我已经删除了除了注释一之外的所有正则表达式:以#开头的行应该是粗体和绿色的:

from PyQt4 import QtGui, QtCore
class Highlighter(QtGui.QSyntaxHighlighter):
    def __init__(self, document):
        QtGui.QSyntaxHighlighter.__init__(self, document)
        rules = []
        style = QtGui.QTextCharFormat()
        style.setForeground(QtGui.QColor('darkGreen'))
        style.setFontWeight(QtGui.QFont.Bold)
        rules.append((r'#[^n]*', style))
        self._rules = [(QtCore.QRegExp(pat), fmt) for (pat, fmt) in rules]
    def highlightBlock(self, text):
        for (pattern, style) in self._rules:
            i = pattern.indexIn(text, 0)
            while i >= 0:
                n = pattern.matchedLength()
                self.setFormat(i, n, style)
                i = pattern.indexIn(text, i + n)
        self.setCurrentBlockState(0)

如果我这样使用荧光笔,效果会很好:

app = QtGui.QApplication([])
editor = QtGui.QPlainTextEdit()
highlight = Highlighter(editor.document())
editor.show()
app.exec_()

但是当我在QMainWindow中使用它时失败了,就像这样:

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        editor = QtGui.QPlainTextEdit()
        highlighter = Highlighter(editor.document())
        self.setCentralWidget(editor)
app = QtGui.QApplication([])
window = MainWindow()
window.show()
app.exec_()

有人能告诉我我做错了什么吗?

谢谢,Michael

您需要保留对荧光笔的引用。所以就这么做吧:

    self.highlighter = Highlighter(editor.document())

编辑

更准确地说:您需要保留对QSyntaxHighlighter子类的python部分的引用。传递给构造函数的父对象将获得荧光笔的所有权,但Qt显然不会自动管理python部分。

真正的区别在于:

    print(repr(self.editor.document().children())) ...
    # without keeping a reference
    [<PyQt4.QtGui.QPlainTextDocumentLayout object at 0x7f8590909b88>
     <PyQt4.QtGui.QSyntaxHighlighter object at 0x7f8590909c18>]
    # with a reference
    [<PyQt4.QtGui.QPlainTextDocumentLayout object at 0x7f56b7898c18>,
     <__main__.Highlighter object at 0x7f56b7898a68>]

因此,除非保留引用,否则重新实现的highlightBlock函数对Qt是不可见的。

最新更新