简体   繁体   中英

Is it possible to create a Qml Component from C++?

Is there some way to create/append a QML Component from C++?

Example, if i have this QML:

Window {
    id: window
    objectName: "windowName"
    title: "windowName"
    width: 480
    height: 800

    Rectangle {
        id: frmHeader
        objectName: "frmHeader"
        width: parent.width
        height: parent.height
    }
}

Is it possible append a TextInput on Rectangle?

In your case you should follow the following steps:

  • find the item using the objectName through findChild.

  • create the item with QQmlComponent

  • add the parent as property.

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlComponent>
#include <QQmlProperty>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    QObject *frmHeader = engine.rootObjects().first()->findChild<QObject *>("frmHeader");
    QQmlComponent component(&engine);
    component.setData("import QtQuick 2.7 \n"
                      "TextInput{ \n"
                      "text: \"hello world :D\" \n"
                      "}", QUrl());
    QObject *text_object = component.create();
    if(text_object && frmHeader)
        Q_ASSERT(QQmlProperty::write(text_object,
                                     "parent",
                                     QVariant::fromValue(frmHeader)));

    return app.exec();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM