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

1

5

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?

Wildwood answered 2/11, 2012 at 8:39 Comment(2)
Isn't this considered a bad practice (access UI elements from c++)? I've been trying myself to learn how to connect my c++ object method to a qml object signal...Renunciation
@JoaoMilasch yes it is. This was just an example. The primary goal was to get the C++ code to react to the button click.Wildwood
C
8

You should surround the object name with quotation marks:

Button {
    objectName: "btnLogin"
    ...
    ...
}
Centavo answered 2/11, 2012 at 10:2 Comment(1)
I guess this mistake comes from the fact that the id property doesn't have quotation marks.Kine

© 2022 - 2024 — McMap. All rights reserved.