Qml Signal - PySide6 Slot Using QObject.findChild()

Finally, we have a Qml signal, a PySide6 slow and the connection is established in PySide6 code. To do this

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
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

ApplicationWindow {

    visible: true
    width: 400
    height:200
    title: "Template App"

    RowLayout {
        
        anchors.fill: parent
        
        Button {
            
            // 1. Make the button available to Python
            //    by giving it a name
            
            objectName: "button"
            
            Layout.fillWidth: true
            Layout.fillHeight: true
            
            text: "Click Me!"
        }
    }
}
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
import sys

from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine

from PySide6.QtCore import QObject, Slot


class Logger(QObject):
    
    @Slot(str)
    def log(self, message):
        print(message)



if __name__ == '__main__':

    app = QGuiApplication(sys.argv)
    
    engine = QQmlApplicationEngine()
    engine.quit.connect(app.quit)
    engine.load('04_rootelement_findchild.qml')
    
    # 2. Use the engine to find the button
    
    root = engine.rootObjects()[0]
    button = root.findChild(QObject, 'button')
    
    # 3. Create a Logger() instance
    #    and connect buttons clicked signal 
    #    to the Logger.log slot
    
    logger = Logger()
    
    button.clicked.connect(
        lambda: logger.log('You clicked me!'))

    result = app.exec()
    del engine
    
    sys.exit(result)
  1. Add a Qml Button to the main window and set its objectName so you can find in in the PySide6 code.

  2. Use QQmlApplicationEngine.rootObjects() to get the main window object reference in the PySide6 code and QObject.findChild() to get the reference to the Button object.

  3. Create a Logger class instance and connect its log() method with the Button’s clicked signal. We don’t need to use Logger in Qml so we don’t decorate it with QmlElement.