Component Creation
Unsolved
QML and Qt Quick
-
I am trying to dynamically create a QML object inside a predefined viewport object in C++ , even though the program works without any errors the actual component is not visible as if it were not there! I am struggling to understand why that is... am I missing something?
main.cpp
int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication hostApp(argc, argv); QUrl mainUrl(QLatin1String("qrc:/main.qml")); QUrl placeholderUrl(QLatin1String("qrc:/placeholder.qml")); QQmlApplicationEngine *engine(new QQmlApplicationEngine()); engine->load(mainUrl); QObject* viewport(engine->rootObjects().first()->findChild<QObject*>("viewport")); QQmlComponent newcomp(engine, placeholderUrl, viewport); QObject* obj(newcomp.create()); return hostApp.exec(); }
qrc:/main.qml
import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.0 import QtGraphicalEffects 1.0 ApplicationWindow { visible: true width: 1024 height: 768 title: qsTr("Test") Rectangle { anchors.fill: parent color: Qt.rgba(.97,.97,.97,1) } Rectangle { id: appwindow anchors.centerIn: parent width: viewport.width height: titlebar.height + viewport.height Rectangle { id: titlebar anchors.left: parent.left anchors.right: parent.right height: 32 anchors.top: parent.top Row { anchors.fill: parent anchors.leftMargin: 8 spacing: 16 Text { text: "Sample Application" font.pixelSize: 12 anchors.verticalCenter: parent.verticalCenter color: Qt.rgba(0,0,0,.6) } } Rectangle { anchors.left: parent.left anchors.right: parent.right anchors.bottom: parent.bottom height: 1 color: Qt.rgba(0,0,0,.05) } } Rectangle { objectName: "viewport" id: viewport anchors.top: titlebar.bottom width: 640 height: 480 color: Qt.rgba(1,1,1,1) } } DropShadow { anchors.fill: appwindow verticalOffset: 24 radius: 64 samples: 64 color: Qt.rgba(0,0,0,.2) source: appwindow } }
qrc:/placeholder.qml
import QtQuick 2.7 Item { id: container anchors.fill: parent Column { anchors.centerIn: parent spacing: 8 Text { text: "Placeholder Component" anchors.horizontalCenter: parent.horizontalCenter } Text { text: container.width + " x " + container.height anchors.horizontalCenter: parent.horizontalCenter } } }
-
I got it to work with the following line:
obj->setProperty("parent", QVariant::fromValue<QObject*>(viewport));
now everything's fine, anyway.. am I doing everything correctly here?
It's strange that it's not documented