Posted on 2020-02-24 14:56
eryar 阅读(4482)
评论(0) 编辑 收藏 引用 所属分类:
2.OpenCASCADE 、
6.Others
Qt Python Scriptable Application
eryar@163.com
Abstract. Python and C++ are in many ways as different as two languages could be: while C++ is usually compiled to machine-code, Python is interpreted. Python's dynamic type system is often cited as the foundation of its flexibility, while in C++ static typing is the cornerstone of its efficiency. C++ has an intricate and difficult compile-time meta-language, while in Python, practically everything happens at runtime.
Key Words. Qt, Python, Shiboken2, PySide2
1 Introduction
Python和C++是两种不同的开发语言:C++通常编译成机器码,而Python是解释型的。Python的动态类型系统是它灵活性的基础,而C++的静态类型运行效率高。对于许多程序员来说,让Python和C++互为补充来进行程序开发是很完美的。Python程序的性能瓶颈可以用C++来重写;C++程序选择Python作为中间脚本语言,可以为程序提供方便地集成和扩展能力,即支持程序二次开发,方便为程序定制功能。
2 Shiboken2
Shiboken2是一个为C/C++库生成CPython绑定代码的生成器,用来创建PySide的模块,换句话说,Shiboken可以用来暴露Qt C++API给Python。
Shiboken使用ApiExtractor库来分析所有的Qt头文件。由于使用的clang,不依赖Qt,所以Shiboken也可用于将非Qt的C++项目。并且Shiboken有一个类型系统Typesytem,基于XML文件。

编译PySide的前提条件就是先要编译出Shiboken。当成功编译PySide后,就会生成Shiboken等类库。既然使用Shiboken可以将Qt的C++对象暴露给Python,那么如何将C++和Python结合起来,生成一个支持Python脚本的程序呢?
在PySide2的例子文件夹中提供了两个例子:
l SampleBinding:暴露非Qt的C++对象给Python;
l ScriptableApplication:支持脚本的程序示例;
如何编译这两个例子,在其中的ReadMe.md中都有详细说明,主要是配置好PySide2,Shiboken2等环境。其中ScriptableApplication中提供了CMake和QMake两种编译方式,将他们生成VS的工程可以看出,在VS项目中增加了XML文件,并将其设置成Custom Build Tool:

并为其配置Shiboken的一些命令选项:

3 ScriptableApplication Example
编译成功程序运行截图如下所示:

程序支持了Python脚本,当然也可以使用PySide来开发GUI,如下所示:

4 Conclusion
为C++程序提供Python脚本支持有很多开源库可以实现,如boost.python, pycxx等,而Qt 的PySide2使用Shiboken2来将Qt的C++类型暴露给Python,所以也可以直接使用Shiboken2来将C++类封装成Python类。
5 References
- Building Hybrid Systems With Boost Python, by Dave Abrahams and Ralf W. Grosse-Kunstleve
- https://wiki.qt.io/Qt_for_Python/Shiboken
- https://doc.qt.io/qtforpython/shiboken2/contents.html
- https://www.qt.io/blog/2018/05/31/write-python-bindings
- https://code.qt.io/cgit/pyside/pyside-setup.git/tree/examples/scriptableapplication
为了方便大家在移动端也能看到我的博文和讨论交流,现已注册微信公众号,欢迎大家扫描下方二维码关注。