Skip to main content
 首页 » 编程设计

python之PyQt4 高亮显示

2025年05月04日10lyhabc

我正在尝试向 PyQt4 中的文本编辑器添加一些语法突出显示。我在文档中找到了一个示例,该示例在从 C++ 编译时可以找到,但是当我将其转换为 Python/PyQt 时,它不再有效。

失败的代码部分(不再突出显示任何内容)是:

def highlightCurrentLine(self): 
 
    extraSelections = [] 
 
    if not self.isReadOnly(): 
        selection = QTextEdit.ExtraSelection() 
 
        lineColor = QColor(Qt.yellow).lighter(160) 
 
        selection.format.setBackground(lineColor) 
        selection.format.setProperty(QTextFormat.FullWidthSelection, QVariant(True)) 
        selection.cursor = self.textCursor() 
        selection.cursor.clearSelection() 
        extraSelections.append(selection) 
 
    self.setExtraSelections(extraSelections) 

调用者:

self.connect(self, SIGNAL('cursorPositionChanged()'), self.highlightCurrentLine) 

有人知道为什么这行不通吗?

我使用的版本是:Python 2.6.2, PyQt 4.4.4

请您参考如下方法:

好吧...事实证明我并没有发疯,我只是在使用 PyQt4 的过时版本。

有关信息,Ubuntu 9.04 附带的 PyQt4 版本是 4.4.4,但此功能似乎需要 4.5+。

我已经升级到 PyQt4 4.6,它工作正常(加上 4.6 似乎也有一些不错的新功能)。