Qt Python Scriptable Application

 

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文件。

Qt Python Scriptable Application 

 Qt Python Scriptable Application

编译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:

 Qt Python Scriptable Application

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

 Qt Python Scriptable Application

3 ScriptableApplication Example

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

 Qt Python Scriptable Application

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

 Qt Python Scriptable Application

4 Conclusion

为C++程序提供Python脚本支持有很多开源库可以实现,如boost.python, pycxx等,而Qt 的PySide2使用Shiboken2来将Qt的C++类型暴露给Python,所以也可以直接使用Shiboken2来将C++类封装成Python类。

5 References

  1. Building Hybrid Systems With Boost Python, by Dave Abrahams and Ralf W. Grosse-Kunstleve
  2. https://wiki.qt.io/Qt_for_Python/Shiboken
  3. https://doc.qt.io/qtforpython/shiboken2/contents.html
  4. https://www.qt.io/blog/2018/05/31/write-python-bindings
  5. https://code.qt.io/cgit/pyside/pyside-setup.git/tree/examples/scriptableapplication

 

原文链接: https://www.cnblogs.com/opencascade/p/QtScriptableApplication.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    Qt Python Scriptable Application

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/331631

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午6:08
下一篇 2023年3月1日 下午6:08

相关推荐