PDA

View Full Version : loading QML file as a component from C++ to QQmlApplicationEngine



kafanti
8th October 2015, 14:03
Hello everyone,

I am trying to load a qml file to my QQmlApplicationEngine. I guess, since the component is visual item(rect), somehow, engine does not render it.
Can someone please point me where am i missing?

Thank you.

Here is my sample code,



/* MyItem.qml */
import QtQuick 2.5

Rectangle {
id: top
property string str: "#FF0000"
color: str
width: 10
height: 20
Component.onCompleted: console.log("myitem ctor", width, height, x, y, visible, color);
}

/* main.qml */
import QtQuick 2.5
import QtQuick.Window 2.2

Window {
visible: true
id: root

MouseArea {
id: mouse
anchors.fill: parent
onClicked: {
Qt.quit();
}
}

Text {
id: text
text: qsTr("Hello World")
anchors.centerIn: parent
}
}

/* main.cpp */
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlComponent>
#include <QQmlEngine>

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

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

QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/MyItem.qml")));

QObject *childItem = component.create();
QList<QObject *> rootObjects = engine.rootObjects();
QObject *parentItem = rootObjects.first();

childItem->setParent(parentItem);

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

return app.exec();
}

anda_skoa
8th October 2015, 15:27
Can you explain what you are trying to do and what does not work?

Cheers,
_