Skip to main content
 首页 » 编程设计

python之PyQt5 中带有可点击文本的 QPlainTextEdit 小部件

2025年04月02日9duanxz

我正在尝试在 PyQt5 中构建一个简单的代码/文本编辑器。我想到了代码编辑器的三个重要功能:
(1) 语法高亮
(2) 代码补全
(3) 可点击的函数和变量

我计划将代码编辑器基于 QPlainTextEdit 小部件。对于语法高亮,我将使用QSyntaxHighlighter:
https://doc.qt.io/qt-5/qsyntaxhighlighter.html#details
我还没有弄清楚如何完成代码,但稍后会担心该功能。现在最引人注目的是“可点击的函数和变量”。在成熟的代码编辑器中,可以单击函数调用并跳转到该函数的定义。变量也是如此。

我知道问“我如何实现此功能?”范围太广了。因此,让我们将其缩小为以下问题:
如何在 QPlainTextEdit 小部件中使某个词可点击?单击单词时应调用任意 Python 函数。该 Python 函数还应该知道单击了哪个词以采取适当的操作。当鼠标悬停在单词上时,让单词亮起蓝色将是一个不错的奖励。

我写了一个小的测试代码,所以你有一个 Qt 窗口,中间有一个 QPlainTextEdit 小部件可以玩:

代码如下:

import sys 
import os 
from PyQt5.QtWidgets import * 
from PyQt5.QtGui import * 
from PyQt5.QtCore import * 
 
################################################## 
#   'testText' is a snippet of C-code that       # 
#   will get displayed in the text editor.       # 
################################################## 
testText = '\ 
# include <stdio.h>\n\ 
# include <stdbool.h>\n\ 
# include <stdint.h>\n\ 
# include "../FreeRTOS/Kernel/kernel.h"\n\ 
\n\ 
int main(void)\n\ 
{\n\ 
    /* Reset all peripherals*/\n\ 
    HAL_Init();\n\ 
\n\ 
    /* Configure the system clock */\n\ 
    SystemClock_Config();\n\ 
\n\ 
    /* Initialize all configured peripherals */\n\ 
    MX_GPIO_Init();\n\ 
    MX_SPI1_Init();\n\ 
    MX_SPI2_Init();\n\ 
    MX_SPI3_Init();\n\ 
}\n\ 
' 
 
################################################## 
#   A simple text editor                         # 
#                                                # 
################################################## 
class MyMainWindow(QMainWindow): 
    def __init__(self): 
        super(MyMainWindow, self).__init__() 
        # Define the geometry of the main window 
        self.setGeometry(200, 200, 800, 800) 
        self.setWindowTitle("text editor test") 
 
        # Create center frame 
        self.centerFrm = QFrame(self) 
        self.centerFrm.setStyleSheet("QWidget { background-color: #ddeeff; }") 
        self.centerLyt = QVBoxLayout() 
        self.centerFrm.setLayout(self.centerLyt) 
        self.setCentralWidget(self.centerFrm) 
 
        # Create QTextEdit 
        self.myTextEdit = QPlainTextEdit() 
        self.myTextEdit.setPlainText(testText) 
        self.myTextEdit.setStyleSheet("QPlainTextEdit { background-color: #ffffff; }") 
        self.myTextEdit.setMinimumHeight(500) 
        self.myTextEdit.setMaximumHeight(500) 
        self.myTextEdit.setMinimumWidth(700) 
        self.myTextEdit.setMaximumWidth(700) 
 
        self.centerLyt.addWidget(self.myTextEdit) 
        self.show() 
 
 
if __name__== '__main__': 
    app = QApplication(sys.argv) 
    QApplication.setStyle(QStyleFactory.create('Fusion')) 
    myGUI = MyMainWindow() 
    app.exec_() 
    del app 
    sys.exit() 

编辑
很长一段时间后,我才重新审视这个问题。与此同时,我建立了一个关于 QScintilla 的网站:https://qscintilla.com
您可以在那里找到所有信息:-)

请您参考如下方法:

也许你可以利用 qutepart .看起来它可以满足您的需求。如果您不会使用它,那么也许您可以查看源代码以了解它们如何实现不同的功能,例如可点击的文本。