PyQt之嵌入VScode

首先,介绍一下Monaco Editor

The Monaco Editor is the code editor that powers VS Code. A good page describing the code editor’s features is here.

It is licensed under the MIT License and supports Edge, Chrome, Firefox, Safari and Opera.

The Monaco editor is not supported in mobile browsers or mobile web frameworks.

Find more information at the Monaco Editor repo.

我们的仿vscode代码编辑器功能基于Monaco Editor(VSCode的内核)实现,通过建立本地html并通过QWebEngineView嵌入QT,使用page().runJavaScript调用js实现代码的设置,并实现代码高亮、自动换行、自动补全等功能

嵌入QT

利用QWebEngineView可以将网页嵌入QT,网页文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<style type="text/css">
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body>

<div id="container" style="width:100%;height:100%"></div>

<!-- 引入base64方法,设置编辑器内容时使用-->
<script src="./base64.js"></script>
<!-- 根据实际路径进行修改 -->
<script src="./package/dev/vs/loader.js"></script>
<script>
// <!-- 根据实际路径进行修改 -->
require.config({paths: {'vs': './package/dev/vs'}});
require(['vs/editor/editor.main'], function () {
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
noSemanticValidation: true,
noSyntaxValidation: true
});
editor = monaco.editor.create(document.getElementById('container'), {
value: "",
language: 'python', //默认语言
mouseWheelZoom:true, // 鼠标滚轮缩放
wordWrap:"on", // 自动换行
scrollBeyondLastLine:true,
//theme: 'vs-dark', // 主题
minimap:{
enabled:true // 显示右侧小地图
}
});
window.onresize = function () {
editor.layout();
};
});
</script>
<script language="javascript">
function test() {
var res = success;
return res;
}
</script>
</body>
</html>

然后将网页嵌入QT中:

1
2
self.editor_index = (os.path.split(os.path.realpath(__file__))[0]) + "/vscode.html"
self.load(QUrl.fromLocalFile(self.editor_index))

最后,通过调用Monaco支持的js完成网页内容赋值

1
2
3
4
5
6
def set_value(self, data):
"""设置编辑器内容"""
data = base64.b64encode(data.encode())
data = data.decode()
self.page().runJavaScript(f"editor.getModels()[0].setValue(Base.decode('{data}'))")
print('set',data)

效果:

0909-2

在线编译

通过以下代码调用cmd即可

注意,需要先安装python并配置环境变量

1
os.system(f'start cmd /K python {filepath}\{filename}')
不要打赏,只求关注呀QAQ