Create and Control a QML Component from C++



  • Hello,
    I am a beginner in qt-qml, I am trying to implement a client-sever application an hmi (a minimal one), the client receives data from server as messages and the client has to display the data on screen, data is nothing but position of an object which varies w.r.t time. single or multiple objects may be there,
    i have implemented the client-server application and i am able to send some text and display it on qml ui.

    But now i want to create a qml component, say a small rectangle, on qml screen when i receive a position data message, and update the position of the rectangle when another message is received for the same object.

    Can a qml component be created/updated/deleted from c++ side, when i receive a message from the server.
    OR
    Can i notify the qml ui that a message has arrived and create/update/delete a component for that message.

    Please tell me how this can be implemented.

    Thanks in Advance
    Georgy Daniel



  • This is how I did it, please go through it and suggest any changes or different approaches for doing the same.

    @QtQuick2ApplicationViewer *viewer = QtQuick2ApplicationViewer::instance();
    QQmlContext *context = viewer->rootContext();
    context->setContextProperty("_client", &client);

    /Main QML File/
    viewer->setMainQmlFile(QStringLiteral("qml/qml-dynamic/main.qml"));
    viewer->showExpanded();

    QQmlEngine *engine = viewer->engine();
    /dynamically loaded component/
    QQmlComponent component(engine, QUrl::fromLocalFile("qml/qml-dynamic/dyn-comp.qml"));
    QObject *object = component.create();

    QQuickItem item = qobject_cast<QQuickItem>(object);

    /In qml, items won't get drawn unless they are parented to the view./
    /* You should always use QObject::setProperty(), QDeclarativeProperty

    • or QMetaProperty::write() to change a QML property value, to ensure
    • the QML engine is made aware of the property change.
      /
      object->setProperty("parent", QVariant::fromValue<QObject
      >(viewer->rootObject()));

    /This works same as setProperty/
    // QQmlProperty::write(object, "parent"
    // , QVariant::fromValue<QObject*>(viewer->rootObject()));

    QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);

    /Set X and Y properties of the item created./
    item->setx(150);
    item->setY(150);@


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.