2
votes

Veteran C++ and C#/WinForms programmer here, getting familiar with Qt/QML.

There's a lot of information on how to call into C++ from QML, and I've got that working just fine, but I'd rather treat QML passively and manipulate it from C++ when at all possible.

For example:

frmLogin::frmLogin()
{
    // Load QML file

    // Wire up controls to their own pointers
    cmdOK = QtQuick_GetControlFromQML("cmdOK");
    cmdQuit = QtQuick_GetControlFromQML("cmdQuit");
}

void frmLogin::Show()
{
    MyQMLPointerToWindow->Show();
}

void frmLogin::DoSomethingFromCPP()
{
    cmdOK->SetProperty("text", "I just changed the button text");
    rectBox->SetProperty("visible", true); // rectBox Rectangle from QML now appears on the screen

    frmMainMenu = new frmMainMenu(); // Create new main menu window
    frmMainMenu->ShowDialog(); // modal display
}

Is there a way to do this? Is it highly discouraged? I'm trying to make a multi-form modal application. It's difficult to find straightforward answers on all of this because it seems like QtQuick has gone through several design iterations. Any advice is appreciated!

1
Why are you using QML at all if you want to do everything in C++?Deadron
Because I want to use Qt Quick GUI system, not traditional Qt.user1054922

1 Answers

4
votes

If you know the objectName of the item you're interested in, you can use QObject::findChild():

QQuickItem *okButton = findChild<QQuickItem*>("cmdOK");

If the button is declared as a property in QML:

Item {
    id: item

    property alias button: item.button

    Button {
        id: button
        text: "OK"
    }
}

Then you can access it as a property in C++:

QObject *button = property("button").value<QObject*>();
button->setProperty("text", "I just changed the button text");