Exposing a PySide6 Property to 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import sys
from PySide6.QtCore import QObject, Slot, Signal, Property
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine, QmlElement
# 1. Set the global variables
QML_IMPORT_NAME = 'examples.logger'
QML_IMPORT_MAJOR_VERSION = 1
# 2. Decorate the class with @QmlElement
# and subclass QObject
@QmlElement
class Logger(QObject):
# 3. Define the signal, the getter and the setter
filenameChanged = Signal(str)
fname_value = '<no name>'
def getFilename(self):
return self.fname_value
def setFilename(self, value):
if value != self.fname_value:
self.fname_value = value
self.filenameChanged.emit(value)
# 4. Declare the property
# notify=... is necessary if the signal name
# does not follow convention.
filename = Property(str, fget=getFilename,
fset=setFilename, notify=filenameChanged)
if __name__ == '__main__':
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('03_property.qml')
result = app.exec()
del engine
sys.exit(result)
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
42
43
44
45
46
47
48
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// 1. Use the QML_IMPORT_NAME value
// to import the Logger class
import examples.logger
ApplicationWindow {
visible: true
width: 400
height:200
title: "Template App"
// 2. Create a Logger object
// onFilenameChanged: Automatic handler!
Logger {
id: logger
onFilenameChanged: {
console.log("The filenameChanged signal emitted");
}
}
RowLayout {
anchors.fill: parent
Button {
text: "Click me!"
Layout.fillWidth: true
Layout.fillHeight: true
font.pointSize:24
font.bold: true
// 3. Use the property
onClicked: {
logger.filename = "03_property.qml";
console.log(logger.filename);
}
}
}
}