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

时间:2016-10-02 12:57:01

标签: python qt pyqt pyqt5

我正在尝试在PyQt5中构建一个简单的代码/文本编辑器。我想到了代码编辑器的三个重要功能:
(1)语法突出显示
(2)代码完成
(3)可点击的功能和变量

我计划将代码编辑器基于QPlainTextEdit小部件。对于语法高亮,我将使用QSyntaxHighlighter
https://doc.qt.io/qt-5/qsyntaxhighlighter.html#details
我还没有想出如何完成代码,但稍后会担心该功能。 showstopper现在是可点击的功能和变量'。在成熟的代码编辑器中,可以单击函数调用并跳转到该函数的定义。变量也是如此
我知道要问"我该如何实现这个功能?"太宽泛了。因此,让我们将其缩小到以下问题:
如何在QPlainTextEdit小部件中点击某个单词?单击单词时应调用任意Python函数。 Python函数还应该知道单击了哪个单词以采取适当的操作。 当鼠标悬停在它上面时,让这个词亮起来是蓝色的。

我已经写了一个小的测试代码,所以你有一个Qt窗口,中间有一个QPlainTextEdit小部件可以用来: enter image description here

以下是代码:

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
你可以在那里找到所有信息: - )

1 个答案:

答案 0 :(得分:1)

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

相关问题