QML Integration Tutorial

This tutorial provides a quick walk-through of a python application that loads, and interacts with a QML file. QML is a declarative language that lets you design UIs faster than a traditional language, such as C++. The QtQml and QtQuick modules provides the necessary infrastructure for QML-based UIs.

In this tutorial, you will learn how to integrate Python with a QML application through a context property. This mechanism will help us to understand how to use Python as a backend for certain signals from the UI elements in the QML interface. Additionally, you will learn how to provide a modern look to your QML application using one of the features from Qt Quick Controls 2.

The tutorial is based on an application that allow you to set many text properties, like increasing the font size, changing the color, changing the style, and so on. Before you begin, install the PySide2 Python packages.

The following step-by-step process will guide you through the key elements of the QML based application and PySide2 integration:

  1. First, let’s start with the following QML-based UI:

    ../../_images/textproperties_default.png

    The design is based on a GridLayout, containing two ColumnLayout. Inside the UI you will find many RadioButton, Button, and a Slider.

  2. With the QML file in place, you can load it from Python:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
        # Instance of the Python object
        bridge = Bridge()
    
        # Expose the Python object to QML
        context = engine.rootContext()
        context.setContextProperty("con", bridge)
    
        # Get the path of the current directory, and then add the name
        # of the QML file, to load it.
        qmlFile = join(dirname(__file__), 'view.qml')
        engine.load(abspath(qmlFile))
    

    Notice that we specify the name of the context property, con, and also we explicitly load our QML file.

  3. Define the Bridge class, containing all the logic for the context property:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    class Bridge(QObject):
    
        @Slot(str, result=str)
        def getColor(self, color_name):
            if color_name.lower() == "red":
                return "#ef9a9a"
            elif color_name.lower() == "green":
                return "#a5d6a7"
            elif color_name.lower() == "blue":
                return "#90caf9"
            else:
                return "white"
    
        @Slot(float, result=int)
        def getSize(self, s):
            size = int(s * 42) # Maximum font size
            if size <= 0:
                return 1
            else:
                return size
    
        @Slot(str, result=bool)
        def getItalic(self, s):
            if s.lower() == "italic":
                return True
            else:
                return False
    
        @Slot(str, result=bool)
        def getBold(self, s):
            if s.lower() == "bold":
                return True
            else:
                return False
    
        @Slot(str, result=bool)
        def getUnderline(self, s):
            if s.lower() == "underline":
                return True
            else:
                return False
    
  4. Now, go back to the QML file and connect the signals to the slots defined in the Bridge class:

    1
    2
    3
    4
    5
    6
    7
    8
    9
                    text: "Bold"
                    onToggled: {
                        leftlabel.font.italic = con.getItalic(bold.text)
                        leftlabel.font.bold = con.getBold(bold.text)
                        leftlabel.font.underline = con.getUnderline(bold.text)
                    }
                }
                RadioButton {
                    id: underline
    

    The properties Italic, Bold, and Underline are mutually exclusive, this means only one can be active at any time. To achieve this each time we select one of these options, we check the three properties via the context property as you can see in the above snippet. Only one of the three will return True, while the other two will return False, that is how we make sure only one is being applied to the text.

  5. Each slot verifies if the selected option contains the text associated to the property:

    1
    2
    3
    4
    5
    6
        @Slot(str, result=bool)
        def getBold(self, s):
            if s.lower() == "bold":
                return True
            else:
                return False
    

    Returning True or False allows you to activate and deactivate the properties of the QML UI elements.

    It is also possible to return other values that are not Boolean, like the slot in charge of returning the font size:

    1
    2
    3
    4
    5
    6
    7
        @Slot(float, result=int)
        def getSize(self, s):
            size = int(s * 42) # Maximum font size
            if size <= 0:
                return 1
            else:
                return size
    
  6. Now, for changing the look of our application, you have two options:

    1. Use the command line: execute the python file adding the option, –style:

      python main.py --style material
      
    2. Use a qtquickcontrols2.conf file:

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      [Controls]
      Style=Material
      
      [Universal]
      Theme=System
      Accent=Red
      
      [Material]
      Theme=Dark
      Accent=Red
      

      Then add it to your .qrc file:

      1
      2
      3
      4
      5
      <!DOCTYPE RCC><RCC version="1.0">
      <qresource prefix="/">
          <file>qtquickcontrols2.conf</file>
      </qresource>
      </RCC>
      

      Generate the rc file running, pyside2-rcc style.qrc > style_rc.py And finally import it from your main.py script.

    1
    2
    3
    4
    5
    6
    7
    8
    import sys
    from os.path import abspath, dirname, join
    
    from PySide2.QtCore import QObject, Slot
    from PySide2.QtGui import QGuiApplication
    from PySide2.QtQml import QQmlApplicationEngine
    
    from style_rc import *
    

    You can read more about this configuration file here.

    The final look of your application will be:

    ../../_images/textproperties_material.png

You can view.qml and main.py to try this example.