是否可以从 C++ 创建 Qml 组件?

问题描述 投票:0回答:2

有什么方法可以从 C++ 创建/附加 QML 组件吗?

例如,如果我有这个 QML:

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

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

是否可以在矩形上附加

TextInput

c++ qt qml qt5 qqmlcomponent
2个回答
3
投票

根据您的情况,您应该按照以下步骤操作:

  • 通过findChild使用objectName查找项目。

  • 使用QQmlComponent创建项目

  • 添加 parent 作为属性。

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();
}

0
投票

注意:为了稍后能够从 C++ 再次访问 TextInput 小部件,请不要忘记指定其 QObject 的父级是 frmHeader,换句话说:

text_object.setParent(frmHeader);
© www.soinside.com 2019 - 2024. All rights reserved.