Change the property of a QML object by C++

Asked

Viewed 87 times

3

I’m trying to change a property of an object (Rectangle) that was instantiated in the QML, but I am not able to perform it because the method findChild returns null.

I am following the following documentations:

-Integrating QML and C++

-Interacting with QML Objects from C++

Main

#include <QApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  QQmlApplicationEngine engine(QUrl("qrc:/main.qml"));

  QQmlContext *ctxt = engine.rootContext();

  QObject *rect = ctxt->findChild<QObject*>("rect");
  if (rect)
          rect->setProperty("color", "blue");
  return app.exec();
}

QML

ApplicationWindow {
    id: app
    title: "Redi"
    width: 640
    height: 480
    visible: true
    visibility : "Maximized"
    Rectangle{
        y:100
        x:100
        width: 100
        height: 100
        objectName: "rect"
    }
}

1 answer

1


I found a solution, but I couldn’t understand why the method findChild returns null. While performing some tests I realized that the method rootObjects returned me an object that possessed the same object of the form that has the object I want to change the property and this way that returns the window I was able to make the change of the property and perform the search of other objects.

Basically the source stayed this way.

Main

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickView>
#include <QQuickItem>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    QObject *rect = engine.rootObjects().first()->findChild<QObject *>("rect");//Alerado de rootContext para rootObjects
    if (rect)
        rect->setProperty("color", "blue");

    return app.exec();
}

Upshot

In Qt Creator design mode inserir a descrição da imagem aqui

In applying inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.