我试图在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。它看起来能满足你的需要。如果您不能使用它,那么您可以查看源代码,看看它们是如何实现不同的功能的,比如可单击的文本。在
相关问题 更多 >
编程相关推荐