Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

setContextProperty or Signal



  • Anyone have thoughts on the issues that could arise with using setContextProperty() to update UI elements instead of Signals?

    Signals require a python function/method & decorator, as well as Connection {} code in the qml file. It's much simpler to just call setContextProperty() again.

    The following examples both work, so Is it safe to use setContextProperty() in this case? Why use signals at all?

    Consider the following (i've paraphrased the code here):

    .py
    
    def update_status(msg):
        root.setContextProperty("statusText", msg)
    
    .qml
    
    Text {
        id: status
        text: qsTr(statusText)
    }
    

    This is a stark contrast to using a slot. (i've paraphrased the code here again)

    .py
    
    class signalClass():
    
        self.messageChanged= QtCore.Signal(str, arguments=['msg'])
    
        def update_status(msg):
            self.messageChanged.emit(msg)
    
    .qml
    
    Text {
        id: status
        text: qsTr(statusText)
        Connections {
            target: signalclass
            onMessageChanged: connectivityStatus.text = qsTr(msg)
        }
    }
    

Log in to reply