How do I react to a QML button click in C++

Tjaart picture Tjaart · Nov 2, 2012 · Viewed 7.1k times · Source

I am trying to launch a different QML Page from my C++ code by hooking into the clicked() slot of a button in my QML but it's not working.

    Button {
        objectName: btnLogin
        text: qsTr("Login")
        id: btnLogin
    }

And the c++

QObject *newButton = root->findChild<QObject*>("btnLogin");
QObject::connect(newButton, SIGNAL(clicked()), this, SLOT(loginClick()));

The slots in my hpp file:

 public slots:  
    void loginClick();

And my clicked method:

void GConnectBB::loginClick() {
    int i = 0;

    Button *newButton = root->findChild<Button*>("btnLogin");
    if (newButton)
        newButton->setProperty("text", "New button text");
}


QObject *newButton = root->findChild<QObject*>("btnLogin"); 

Is null when I check through the debugger. I am extremely rusty with C++ and completely new to Qt, please be gentle :) What could I be doing wrong?

Answer

Nishant Shah picture Nishant Shah · Nov 2, 2012

You should surround the object name with quotation marks:

Button {
    objectName: "btnLogin"
    ...
    ...
}