Expose a PySide6 object to QML using QQMlApplicationEngine.setInitialProperties()

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, Property, Slot
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine

# 1. Create a QObject subclass

class Logger(QObject):
    
    
    fname_value = ''
    
    @Property(str)
    def filename(self):
        return self.fname_value
    
    @filename.setter
    def filename(self, value):
        if value != self.fname_value:
            self.fname_value = value
    
    @Slot(str)
    def log(self, message):
        print(self.filename, ':', message)    

if __name__ == '__main__':

    app = QGuiApplication(sys.argv)
    
    engine = QQmlApplicationEngine()
    engine.quit.connect(app.quit)
    
    # 3. Create a Logger object
    
    logger = Logger()
    
    # 4. Use QQMlApplicationEngine.setInitialProperties()
    #    to set the QML ApplicationWindow.logger property.
    #    The setInitialProperties argument is a dictionary.
    
    engine.setInitialProperties({'logger': logger})
    
    engine.load('06_setinitialproperties.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
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

ApplicationWindow {

    visible: true
    width: 400
    height:200
    title: "Template App"
    
    // 2. Add a property named logger to ApplicationWindow
    
    property var logger

    RowLayout {
        
        anchors.fill: parent
            
        Button {
            text: "Click me!"

            Layout.fillWidth: true
            Layout.fillHeight: true
            
            font.pointSize:24
            font.bold: true
            

            onClicked: {
                logger.filename = "06_setinitialproperties.qml";
                logger.log("Message from QML");
            }
        }
    }
}