Qt for Python

General Introduction

For internal and external distribution

Naming

Qt for Python is the global name of the project.

The story of PySide

Release information

  • Qt for Python (Qt 5.11) - Technical Preview
  • Qt for Python (Qt 5.12) - Official Initial Release
  • Qt for Python (Qt 6.6.1) - Latest release
  • Releases follow the Qt releases
    • Qt5 latest is 5.15.2 OSS and 5.15.16 Commercial LTS
    • Qt6 latest is 6.6.1 OSS and 6.6.1 Commercial LTS

(Slide updated on 08.12.2023)

Python Compatibility

  • PySide2 (5.15)
    • Python 2.7
    • Python 3.6 or greater
  • PySide6 (6.x)
    • Python 3.6+ is required for 6.0, 6.1, 6.2 and 6.3
    • Python 3.7+ is required for 6.4+
    • Python 3.8+ is required for 6.6+

License (1/3)

  • LGPLv3/GPLv3 for Community users (OSS)
    • The tools we included are GPLv3
      pyside6-uic, pyside6-rcc,
      pyside6-designer
      etc.
    • shiboken_generator is GPLv3
    • Qt libraries licenses depend on the module
      (*.so, *.dll, *.dylib)
    • Everything else is LGPLv3

License (2/3)

  • Commercial features included in the
    "Qt for Application Development Professional".
    • Community content
    • LTS releases
    • Shiboken Wizard

License (3/3)

  • Commercial features included in the
    "Qt for Application Development Enterprise" onward.
    • AD Professional content
    • Only 3 modules from the Qt M2M (previously Qt for Automation) Protocols
      (QtOpcUa, QtMqtt, QtCoAp)

Setup πŸ”¨

Installation (1/2)

  • Distributed via Python Packages (.whl files)
    • The official Python interpreter is supported - python.org
    • The official PyPy interpreter is supported - pypy.org
    • conda is supported(starting from 6.4.3) - anaconda.com
  • Python Package Index is supported (only for OSS users)- pypi.org

Installation (2/2)

  • Community (OSS) and Commercial installations are different processes.

Community Edition (OSS)

How to install

Community Edition (OSS)

What is installed?


     β–ͺ️PySide6
      β”œβ”€β”€ Qt modules              βœ…
      β”œβ”€β”€ pyside6-designer        βœ…
      β”œβ”€β”€ pyside6-rcc             βœ…
      β”œβ”€β”€ pyside6-uic             βœ…
      └── ...tools                βœ…
     β–ͺ️Shiboken6 (module)
      └── shiboken6               βœ…
     β–ͺ️Shiboken6_Generator (exe)
      └── shiboken6               ❌
    

Community Edition (OSS)

Installing shiboken6_generator

Community Edition (OSS)

Installing Shiboken Generator

from source

  • Set CLANG_INSTALL_DIR to the libclang directory

    $ python setup.py install
    # there are many other options!
    
doc.qt.io/qtforpython/gettingstarted.html

Commercial Edition (AD, DC)

How to install (Option 1)

  • Download packages (.whl files) from account.qt.io
  • Installing them on a terminal:
  • 
                $ pip install shiboken6-xxxx.whl \
                    pyside6-essentials-xxxx.whl \
                    pyside6-addons-xxxx.whl
                

(xxxx contains information about architecture, OS and the PySide, Qt, and Python versions)

Commercial Edition (AD, DC)

How to install (Option 2)

  • Download them from the Qt Installer
  • Installing them on a terminal:

       $ cd /path/to/Qt/QtForPython/6.6.1
       $ pip install -r requirements.txt
       # The txt file contains the info
       # for all the packages next to them.
       

Commercial Edition (AD, DC)

How to install (Option 3)


       $ pip install qtpip
       $ qtpip install pyside6
       

Commercial Edition (AD Professional)

What is installed?


     β–ͺ️PySide6
      β”œβ”€β”€ Qt modules              βœ…
      β”œβ”€β”€ pyside6-designer        βœ…
      β”œβ”€β”€ pyside6-rcc             βœ…
      β”œβ”€β”€ pyside6-uic             βœ…
      β”œβ”€β”€ ...tools                βœ…
      └── shiboken-wizard         βœ…πŸ†•
     β–ͺ️Shiboken6 (module)
      └── shiboken6               βœ…
     β–ͺ️Shiboken6_Generator (exe)
      └── shiboken6               βœ…
    

Commercial Edition (AD Enterprise, DC Professional/Enterprise)

What is installed?


     β–ͺ️PySide6
      β”œβ”€β”€ Qt modules              βœ…
      β”œβ”€β”€ Qt M2M Protocols        βœ…πŸ†•
      β”œβ”€β”€ pyside6-designer        βœ…
      β”œβ”€β”€ pyside6-rcc             βœ…
      β”œβ”€β”€ pyside6-uic             βœ…
      β”œβ”€β”€ ...tools                βœ…
      └── shiboken-wizard         βœ…πŸ†•
     β–ͺ️Shiboken6 (module)
      └── shiboken6               βœ…
     β–ͺ️Shiboken6_Generator (exe)
      └── shiboken6               βœ…
    

Language differences

Python and C++

C++

  • General purpose and
    Multi-paradigm

C++

  • Statically typed
    
                    int a = 1;
                    float b = 4.3;
                    string c = "hello";

C++

  • Compiled
    
                $ g++ main.cpp -o main
                $ ./main

C++

  • Provides low-level memory manipulation
    
                QObject *obj = new QObject(...);
                delete obj;

C++

  • Code readability
    
                #include <iostream>
    
                int main(int argc, char *argv[]) {
                    std::cout << "Hello World" << endl;
                }

Qt Example

QMainWindow with a QPushButton
C++

        #ifndef MAINWINDOW_H
        #define MAINWINDOW_H

        #include <QMainWindow>
        #include <QPushButton>

        class MainWindow : public QMainWindow
        {
            Q_OBJECT
            public:
                MainWindow(QWidget *parent = nullptr);
            private slots:
                void handleButton();
            private:
                QPushButton *m_button;
        };

        #endif // MAINWINDOW_H

        #include "mainwindow.h"

        MainWindow::MainWindow(QWidget *parent)
           : QMainWindow(parent)
        {
            m_button = new QPushButton("My Button", this);
            connect(m_button, SIGNAL(clicked()), this, SLOT(handleButton()));
        }

        void MainWindow::handleButton()
        {
            m_button->setText("Ready");
        }

        #include <QApplication>
        #include "mainwindow.h"

        int main(int argc, char *argv[])
        {
            QApplication app(argc, argv);
            MainWindow mainWindow;
            mainWindow.show();
            return app.exec(d);
        }
Python

        import sys
        from pyside6.QtWidgets import QApplication, QMainWindow, QPushButton

        class MainWindow(QMainWindow):
            def __init__(self, parent=None):
                QMainWindow.__init__(self, parent)
                self.button = QPushButton("My Button", self)
                self.button.clicked.connect(self.handleButton)

            def handleButton(self):
                self.button.setText("Ready")

        if __name__ == "__main__":
            app = QApplication(sys.argv)
            mainWindow = MainWindow()
            mainWindow.show()
            sys.exit(app.exec())

Qt Compatibility

Checked on 6.6

Qt Essentials

Core D-Bus GUI Network
QML Quick Quick Controls Quick Dialogs
Quick Layouts Quick Test Test Widgets

Some modules could be incomplete, please see wiki.qt.io/Qt_for_Python_Missing_Bindings for more information.

Qt Add-Ons

Active Qt 3D Bluetooth Concurrent
Help Image Formats Multimedia NFC
OPC UA OpenGL PDF Positioning
Print Support Quick Widgets Quick Effects Quick Particles
Remote Objects SCXML Sensors Serial Bus
Serial Port Shader Tools SpatialAudio SQL
StateMachine SVG TextToSpeech UI Tools
WebChannel WebEngine WebSockets WebView
XML Charts CoAP Data Visualization
Lottie Animation MQTT Network Authorization Quick 3D
Quick 3D Physics Quick Timeline Virtual Keyboard Wayland Compositor

Some modules could be incomplete, please see wiki.qt.io/Qt_for_Python_Missing_Bindings for more information.

QML only modules, no C++ classes to expose to Python

Qt Add-Ons (Technical Preview)

HTTP Server Protobuf Graphs GRPC Location

Won't do due to Python equivalent modules out there

Value-Add Modules

Qt Automotive Suite Qt M2M Protocols (1) Qt for Device Creation (2) Qt for MCU (2)

(1) KNX is not included, Only MQTT, CoAp, and OpcUA.

(2) Currently in progress to include Qt for Python in Yocto images

(3) The main Python interpreter doesn't have official support on Microcontrollers. Micro/Circuit Python are subsets of Python, and we don't support them.

Platforms

Windows Linux
macOS Android (1)
iOS (2) WebAssembly (3)
Embedded (4)

  • (1) Deployment via pyside6-android-deploy
  • (2) Python doesn't have official support for iOS
  • (3) Ongoing research
  • (4) aarch64 wheels available on PyPi (>= 6.6). Cross compilation in RaspberryPi OS and Poky linux is possible.

Binding generation

Shiboken

Generation process

Shiboken
ζ­»ζŸε‰£

doc.qt.io/qtforpython/shiboken6

Shiboken

Module

import shiboken6

  • Helper functions
    • isValid(obj)
    • getCppPointer(obj)
    • isOwnedByPython(obj)
    • VoidPtr class

Qt Creator

Qt Creator compatibility

Qt Creator templates

  • Empty application,
  • Basic Widget application,
  • Basic Widget application (.ui file), from 4.12,
  • QtQuick application (QML), from 4.12.

Qt Creator functionality


Can
  • Create new projects,
  • Syntax highlight,
  • Code completion,
  • Add/remove files,
  • Generate Python code from ui and qrc files,
  • Install PySide wheels,
  • Execute applications,
  • Select Python interpreter.
Cannot
  • Install new Python modules,
  • Remote debugging.

What's there besides the Qt API?

Added value

Qt's a C++ framework, and that might be confusing.
  • camelCase API is not a Python standard
  • The usage of setters/getters is not common, in favor of writable properties
  • Qt has data structures to improve C++'s developers life, but Python too.

The __feature__ option


      # Common Qt structure
      # - Using setter/getter
      # - No writable properties

      table = QTableWidget()
      table.setColumnCount(2)

      button = QPushButton("Add")
      button.setEnabled(False)

      layout = QVBoxLayout()
      layout.addWidget(table)
      layout.addWidget(button)
      

Python compatibility

  • Usage of Python native structures instead of QVariant
  • Sequences (Python Lists, Tuples, etc) instead of Qt Sequences
  • Compatibility with pathlib objects (>=6.2)
  • Usage of numpy.array instead of numerical arrays

Python's asyncio support

  • Support via trio module
  • Support via QtAsyncio a self-made wrapper around the Qt event loop, that's complaint with the asyncio definition.

Included Qt tools (1/2)

Wrapper tools included with the PySide6 package
  • Widget Development
    • pyside6-designer, drag-and-drop tool for designing Widget UIs (generates .ui files.
    • pyside6-uic, to generate Python code from .ui form files.
    • pyside6-rcc, to generate serialized data from .qrc resources files
  • Translations
    • pyside6-linguist, for translating text in applications.
    • pyside6-lrelease, to create run-time translation files for the application.
    • pyside6-lupdate, to synchronize source code and translations.
  • QtHelp
    • pyside6-assistant, for viewing online documentation in Qt Help file format.

Included Qt tools (2/2)

Wrapper tools included with the PySide6 package
  • QML development
    • pyside6-qmllint, that verifies the syntactic validity of QML files.
    • pyside6-qmltyperegistrar, to read metatypes files and generate files that contain the necessary code to register all the types marked with relevant macros.
    • pyside6-qmlimportscanner, to identify the QML modules imported from a project/QML files and dump the result as a JSON array.
    • pyside6-qmlcachegen, to compile QML to bytecode at compile time for bundling inside the binary.
    • pyside6-qmlsc, that replaces pyside6-qmlcachegen. This tool generates C++ code in addition to byte code for functions it can exhaustively analyze. pyside6-qmlsc is commercial only.

Extra tools (1/2)

Ad-hoc tools included with the PySide6 package
  • Utilities
    • pyside6-genpyi, to generate Python stubs (.pyi files) for Qt modules.
    • pyside6-metaobjectdump, a tool to print out the metatype information in JSON to be used as input for qmltyperegistrar.
  • Deployment
    • pyside6-deploy, to deploy PySide6 applications to desktop platforms - Linux, Windows and macOS.
    • pyside6-android-deploy, to deploy PySide6 application as an Android app targeting different Android platforms - aarch64, armv7a, i686, x86_64.

Extra tools (2/2)

Ad-hoc tools included with the PySide6 package
  • pyside6-project, to build Qt Designer forms (.ui files), resource files (.qrc) and QML type files (.qmltype) from a .pyproject file.

% pyside6-project -h
usage: project.py [-h] [--quiet] [--dry-run] [--force] [--qml-module]
                  {build,run,clean,qmllint,deploy,new-quick,new-ui,new-widget} [file]

Builds a '.pyproject' file

Builds Qt Designer forms, resource files and QML type files

Deploys the application by creating an executable for the corresponding platform

For each entry in a '.pyproject' file:
- .pyproject: Recurse to handle subproject
- .qrc      : Runs the resource compiler to create a file rc_.py
- .ui       : Runs the user interface compiler to create a file ui_.py

For a Python file declaring a QML module, a directory matching the URI is
created and populated with .qmltypes and qmldir files for use by code analysis
tools. Currently, only one QML module consisting of several classes can be
handled per project file.

positional arguments:
  {build,run,clean,qmllint,deploy,new-quick,new-ui,new-widget}
                        build    Builds the project
                        run        Builds the project and runs the first file")
                        clean      Cleans the build artifacts")
                        qmllint    Runs the qmllint tool
                        deploy     Deploys the application
                        new-ui     Creates a new QtWidgets project with a Qt Designer-based main window
                        new-widget Creates a new QtWidgets project with a main window
                        new-quick  Creates a new QtQuick project
  file                  Project file

options:
  -h, --help            show this help message and exit
  --quiet, -q           Quiet
  --dry-run, -n         Only print commands
  --force, -f           Force rebuild
  --qml-module, -Q      Perform check for QML module

    
    

Shiboken Wizard

Easy graphical way to generate Python bindings from a C++ project.

Shiboken Wizard

Overview video

Common Use Cases

Pure Python Applications

Custom Python Bindings (without Qt)

Generating Python bindings
from a C++ library.

  • Library files:
    • CMakeLists.txt
    • icecream.cpp
    • icecream.h
    • truck.cpp
    • truck.h
  • Shiboken files:
    • bindings.h (right top)
    • bindings.xml (right bottom)

β˜… Check the samplebinding example


        #ifndef BINDINGS_H
        #define BINDINGS_H

        #include "icecream.h"
        #include "truck.h"

        #endif // BINDINGS_H
<typesystem package="Universe"> <primitive-type name="bool"/> <primitive-type name="std::string"/> <object-type name="Icecream"> <modify-function signature="clone()"> <modify-argument index="0"> <define-ownership owner="c++"/> </modify-argument> </modify-function> </object-type> <value-type name="Truck"> <!-- Same ownership caveat applies here. --> <modify-function signature="addIcecreamFlavor(Icecream*)"> <modify-argument index="1"> <define-ownership owner="c++"/> </modify-argument> </modify-function> </value-type> </typesystem>

Custom Python Bindings (with Qt)

Simple typesystem

<typesystem package="wiggly"> <load-typesystem name="typesystem_widgets.xml" generate="no"/> <object-type name="WigglyWidget"/> </typesystem>

Python usage

from wiggly import WigglyWidget as WigglyWidgetCPP
from wigglywidget import WigglyWidget as WigglyWidgetPY

# ...
wiggly_widget_py = WigglyWidgetPY(self)
wiggly_widget_cpp = WigglyWidgetCPP(self)
# ...
layout.addWidget(wiggly_widget_py)
layout.addWidget(wiggly_widget_cpp)
      

β˜… Check the widgetbinding example


  • Top: Widget written in Python
  • Bottom: Widget written in C++ (exposed to Python)

Hybrid Applications (Python and C++)

Embedding Python into a Qt/C++ application

The Text editor interprets Python code to access the Qt/C++ application to modify it.

β˜… Check the scriptableapplication example

Final remarks

Future steps

  • More tutorials and examples,
  • Continue improving C++/Python interaction,
  • IDE integration (QtCreator, Qt Design Studio, and VSCode),

For more details, refer to our blog posts
qt.io/blog/tag/qt-for-python

Where to start

Webinars

Communication channels

More platforms at wiki.qt.io/Qt_for_Python#Community

Qt for Python

General Introduction

Dr. CristiΓ‘n Maureira-Fredes
Senior R&D Manager @ TQtC