我想在PyQt5中建立一個簡單的代碼/文本編輯器。代碼編輯器的三個重要功能來我的腦海:
(1)語法高亮
(2)代碼完成
(3)可點擊函數和變量
我打算基地在QPlainTextEdit
小部件上的代碼編輯器。對於語法突出顯示,我將使用QSyntaxHighlighter
:
我還沒有想出如何完成代碼,但稍後會擔心該功能。 showstopper現在是'可點擊的函數和變量'。在成熟的代碼編輯器中,可以點擊一個函數調用並跳轉到該函數的定義。這同樣適用於變量。
我知道問「我該如何實現此功能?」太寬泛了。因此,讓我們縮小到以下問題:
如何在QPlainTextEdit
小部件中使某個單詞可點擊?當單詞被點擊時應該調用任意的Python函數。 Python函數也應該知道單詞被點擊以採取適當的行動。當鼠標懸停在它上面時,讓這個詞點亮藍色將是一個不錯的獎勵。
我已經寫了一個小的測試代碼,所以你必須在中間一個QPlainTextEdit
部件Qt的窗口打轉轉: QPlainTextEdit小部件在PyQt5與可點擊的文本
下面是代碼:
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
你可以找到:-)
使用[QScintilla](http://pyqt.sourceforge.net/Docs/QScintilla2/):它支持大部分(如果不是全部)你想要的內容。 – ekhumoro
我試過QScintilla。我以某種方式得到了語法高亮工作。但是QScintilla的Python端口的文檔幾乎不存在,或者說至少可以說是很窮。你知道一個很好的教程@ekhumoro嗎? –
不,我只是使用官方文檔加上[Scintilla](http://www.scintilla.org/ScintillaDoc.html)本身的文檔。我敢肯定,一點谷歌搜索會給你一些基本的例子,並且必須有一些關於SO的東西。 – ekhumoro