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++是兩種不同的開發(fā)語言:C++通常編譯成機(jī)器碼,而Python是解釋型的。Python的動(dòng)態(tài)類型系統(tǒng)是它靈活性的基礎(chǔ),而C++的靜態(tài)類型運(yùn)行效率高。對(duì)于許多程序員來說,讓Python和C++互為補(bǔ)充來進(jìn)行程序開發(fā)是很完美的。Python程序的性能瓶頸可以用C++來重寫;C++程序選擇Python作為中間腳本語言,可以為程序提供方便地集成和擴(kuò)展能力,即支持程序二次開發(fā),方便為程序定制功能。
2 Shiboken2
Shiboken2是一個(gè)為C/C++庫生成CPython綁定代碼的生成器,用來創(chuàng)建PySide的模塊,換句話說,Shiboken可以用來暴露Qt C++API給Python。
Shiboken使用ApiExtractor庫來分析所有的Qt頭文件。由于使用的clang,不依賴Qt,所以Shiboken也可用于將非Qt的C++項(xiàng)目。并且Shiboken有一個(gè)類型系統(tǒng)Typesytem,基于XML文件。

編譯PySide的前提條件就是先要編譯出Shiboken。當(dāng)成功編譯PySide后,就會(huì)生成Shiboken等類庫。既然使用Shiboken可以將Qt的C++對(duì)象暴露給Python,那么如何將C++和Python結(jié)合起來,生成一個(gè)支持Python腳本的程序呢?
在PySide2的例子文件夾中提供了兩個(gè)例子:
l SampleBinding:暴露非Qt的C++對(duì)象給Python;
l ScriptableApplication:支持腳本的程序示例;
如何編譯這兩個(gè)例子,在其中的ReadMe.md中都有詳細(xì)說明,主要是配置好PySide2,Shiboken2等環(huán)境。其中ScriptableApplication中提供了CMake和QMake兩種編譯方式,將他們生成VS的工程可以看出,在VS項(xiàng)目中增加了XML文件,并將其設(shè)置成Custom Build Tool:

并為其配置Shiboken的一些命令選項(xiàng):

3 ScriptableApplication Example
編譯成功程序運(yùn)行截圖如下所示:

程序支持了Python腳本,當(dāng)然也可以使用PySide來開發(fā)GUI,如下所示:

4 Conclusion
為C++程序提供Python腳本支持有很多開源庫可以實(shí)現(xiàn),如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
為了方便大家在移動(dòng)端也能看到我的博文和討論交流,現(xiàn)已注冊(cè)微信公眾號(hào),歡迎大家掃描下方二維碼關(guān)注。