Python-based context properties

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 PySide6 Python packages.

The following step-by-step process will guide you through the key elements of the QML based application and PySide6 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    # Instance of the Python object
     3    bridge = Bridge()
     4
     5    # Expose the Python object to QML
     6    context = engine.rootContext()
     7    context.setContextProperty("con", bridge)
     8
     9    # Get the path of the current directory, and then add the name
    10    # of the QML file, to load it.
    11    qmlFile = Path(__file__).parent / 'view.qml'
    

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

    1                text: "Bold"
    2                onToggled: {
    3                    leftlabel.font.italic = con.getItalic(bold.text)
    4                    leftlabel.font.bold = con.getBold(bold.text)
    5                    leftlabel.font.underline = con.getUnderline(bold.text)
    6                }
    7            }
    8            RadioButton {
    9                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    @Slot(str, result=bool)
    3    def getBold(self, s):
    4        if s.lower() == "bold":
    5            return True
    6        else:
    

    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    @Slot(float, result=int)
    3    def getSize(self, s):
    4        size = int(s * 42) # Maximum font size
    5        if size <= 0:
    6            return 1
    7        else:
    
  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[Controls]
       2Style=Material
       3
       4[Universal]
       5Theme=System
       6Accent=Red
       7
       8[Material]
       9Theme=Dark
      10Accent=Red
      

      Then add it to your .qrc file:

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

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

    1import sys
    2import os
    3from pathlib import Path
    4
    5from PySide6.QtCore import QObject, Slot
    6from PySide6.QtGui import QGuiApplication
    7from PySide6.QtQml import QQmlApplicationEngine
    8
    

    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.