Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.

Qt for Python/Porting guide

From Qt Wiki
Jump to navigation Jump to search

Qt for Python is an offering that enable developing Qt applications in a pythonic way. I guess, that didn't go well with most you who have been using Python for years! Let's try to rephrase, Qt for Python is a binding for Qt, to enable Python application development using Qt. Ah..that sounds about right! Isn't it? So, the idea behind Qt for Python is probably clear now. Let's see what does it take to port an existing Qt C++ application to Python. Before we start digging deeper into this topic, let's ensure that we have all the prerequisites met. For example, installing either Python2 or Python3, and so on. Wait a minute, isn't this information outlined in the Getting started section of the documentation. In that case, let's dive straight into the topic.

Assuming that you have required environment to develop Python applications using PySide2(Qt for Python), let's get started. But, we need a C++-based Qt application to port. Let's pick a Qt example that has the .ui XML file, defining the application's UI. That way, we avoid the need to write the code to create a UI. Wait a minute, isn't that the reason why Qt was developed in the first place?

Before we get started, let's familiarize ourselves with some of the basic differences between C++ and Python code:

  • C++ being an object-oriented programming language, we reuse code that is already defined in another file, using the "#include" statements at the beginning. Similarly, we use "import" statements in Python to access packages and classes. Here are is the classic Hello World example using the Python bindings for Qt (PySide2):
import sys
from PySide2.QtWidgets import QApplication, QLabel
                                                     
if __name__ == "__main__":
    app = QApplication(sys.argv)
    label = QLabel("Hello World")
    label.show()
    sys.exit(app.exec_())

Notice, that the application code begins with a couple of import statements to include the sys, and QApplication and QLabel classes from PySide2.QtWidgets.

  • Similar to a C++ application, the Python application also needs an entry point. Not because a Python application must have one, but because it is a good practice to have one. In the Hello World example code that we looked at earlier, you can see that the entry point is defined by the following line:
if __name__ == "__main__":
   #...
  • Qt is popular for its ability to know