PySide6 QtQuick script that shows a label
Unlike the Qt Widgets Hello, World! script this one consists of two files: one written in Qml, a Qt declarative language used to design a QtQuick user interface and the other written in Python, used to actually show the Qui and start the QtQuick application.
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
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// 1. Create an instance of
// the ApplicationWindow Qml type
// and set its properties
ApplicationWindow {
visible: true
width: 400
height:200
title: "Template App"
// 2. Add a layout to the application window
// and add a Label Qml type instance to it.
RowLayout {
anchors.fill: parent
Label {
text: "Hello Qml!"
Layout.fillWidth: true
Layout.fillHeight: true
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
font.pointSize:24
font.bold: true
color: "steelblue"
}
}
}
On the Qml side of things, after the necessary imports
-
Create an instance of the
ApplicationWindow
Qml type. Similarly toQMainWindow
,ApplicationWindow
is a top-level window with support for menus, a header and a footer. Qml components form a hierarchy so allApplicationWindow
child components are declared within its curly braces, along with its properties. In the example we set the window size and title. Don’t forget to setApplicationWindow.visible
totrue
. -
Add a layout to
ApplicationWindow
. In the example,ApplicationWindow
’s only child is aRowLayout
whose only child component, in turn, is aLabel
which displays a message that says ‘Hello Qml!’
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
import sys
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
if __name__ == '__main__':
# 1. Create a QGuiApplication instance
app = QGuiApplication(sys.argv)
# 2. Create a QQmlApplicationEngine instance and connect
# its quit signal with QGuiApplication.quit()
engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
# 3. Load the Qml file
engine.load('01_hello_world.qml')
# 4. Start the main event loop
sys.exit(app.exec())
Back in Python/Pyside6 we
-
Create an instance of the
QGuiApplication
class.QGuiApplication
is suitable for QtQuick applications just asQApplication
is suitable for Qt Widget applications while you would useQCoreApplication
for non-Gui Qt applications. SinceQGuiApplication
handles your application initialization you must create it before any other objects related to the user interface. -
Create an instance of the
QQmlApplicationEngine
class and connect itsquit
signal to theQGuiApplication.quit()
slot to make sure both the application and the engine exit at the same time. -
Use
QQmlApplicationEngine.load()
to load the Qml file.QQmlApplicationEngine
is a convenience class that lets you load a single Qml file into your application. -
Finally use
QGuiApplication.exec()
to start the main event loop.