Search code examples
c++qtqmlsignals-slots

QT - Connect Qml button Click to Cpp Constructor


Here is my code (which doesn't compile, saying: "expected primary-expression before ‘,’ token" while marking the connect in main.cpp)

main.cpp

QObject *myButton = engine.rootObjects().first() -> findChild<QObject*>("btn");
QObject::connect(myButton, SIGNAL(clicked()), MyClass, SLOT(MyClass()));

main.qml

ApplicationWindow {
    id: appWindow
    visible: true
    width: 850; height: 500
Button
{
objectName: btn
anchors.centerIn: parent
}
}

I want the cpp class MyClass to be instantiated every time the button is clicked.

I previously did a different thing, but it had the problem of instantiating MyClass when the application runs, and not when the button is clicked. Furthermore, I couldn't invoke the constructor but a Q_INVOKABLE public method only.

main.cpp

MyClass myClass;
engine.rootContext() -> setContextProperty("_btn", &myClass);

main.qml

ApplicationWindow {
    id: appWindow
    visible: true
    width: 850; height: 500
Button
{
objectName: btn
anchors.centerIn: parent
onClicked: _btn.myMethod() //where myMethod is a Q_INVOKABLE public method belonging to MyClass.
}
}

Solution

  • Please have a look at QObject::connect definition

    QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
    

    Parameter 1 and 3 are instances( not definition as you stated in your snippet ) of QObject-based class, so you need an instance of you class to use signal-slot mechanism. That's the reason of your compilation failure.

    To fullfill your task you have to create some "proxy" class and connect to is slot, where you'll create MyClass dynamically.