Search code examples
c++qtqmlsignals-slots

Connect C++ signal to QML slot


I'm trying to connect a C++ signal with a QML slot.

The C++ signal is called userRegistered() and the QML slot is called userRegisteredQML().

In the C++ file, I have the following:

QQuickView view(QUrl::fromLocalFile("interface.qml"));

QObject *topLevel = view.rootContext();

connect(myClass, SIGNAL(userRegistered()), topLevel, SLOT(userRegisteredQML()));

And in the interface.qml, I have the slot userRegisteredQML:

function userRegisteredQML(){
    console.log("this is a test!");
}

The problem is that it does not show "this a test!". Therefore, I wanted to ask you if this is the proper way to connect a C++ signal to a QML slot.


Solution

  • Expose your object to QML in C++:

    topLevel->setContextProperty("myClass", myClass);
    

    In QML, you can use Connections:

    Connections {
        target: myClass 
        userRegistered: {
            // do something with it here
        }
    }