Create and Control a QML Component from C++
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.
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
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();
/Main QML File/
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.
/This works same as setProperty/
// QQmlProperty::write(object, "parent"
// , QVariant::fromValue<QObject*>(viewer->rootObject()));
/Set X and Y properties of the item created./