簡體   English   中英

如何將動態創建的QQuickitem添加到應用程序的main.qml或QML項目列表中

[英]How to add a dynamically created QQuickitem to my application's main.qml or the QML list of items

我需要動態創建一個QQuickitem並將其添加到我的main.qml

為了做到這一點,我以下面的方式創建了一個QQuickitem

qml_engine->load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
// Creating my QQuickItem here
QQuickItem * dynamic_quick_item = new QQuickItem();
dynamic_quick_item->setObjectName("DynamicQuickItemObject");
dynamic_quick_item->setHeight(500);
dynamic_quick_item->setWidth(500);

dynamic_quick_item->setParent(qml_engine->parent());

我可以訪問main.cpp QQmlApplicationEngine

問題:如何將dynamic_quick_item添加到main.qml項目? 我想從C ++方面將dynamic_quick_item動態添加到main.qml中的項目列表中。

不必將其添加到main.qml 只想將QQuickItem添加到在main.qml中定義的QML項目列表中,這與在main.qml定義的其他QML項目非常main.qml 有沒有可能實現這一目標的方法?

更新:執行以下操作應獲取我添加的QQuickItem的有效實例。 但這不是

QQuickItem *my_dynamic_quickitem = qml_engine->rootObjects()[0]->findChild<QQuickItem*>("DynamicQuickItemObject");

我將my_dynamic_quickitem為null,這意味着我創建的QQuickItem從未添加

可以使用QQmlComponent動態加載QML項目。 QQmlComponent將QML文檔作為C ++對象加載,然后可以從C ++代碼進行修改。

您可以在本指南中找到詳細說明, 網址為http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html#loading-qml-objects-from-c

這是動態創建QML對象並將其放入QML文件的示例。

#include <QGuiApplication>
#include <QQmlComponent>
#include <QQmlEngine>
#include <QQuickItem>
#include <QQuickView>

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

    // Init the view and load the QML file.
    QQuickView view;
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.setSource(QUrl("qrc:///closeups/closeups.qml"));

    // The size of the window
    view.setMinimumSize(QSize(800, 600));

    // Create Text QML item.
    QQmlEngine* engine = view.engine();
    QQmlComponent component(engine);
    component.setData("import QtQuick 2.0\nText {}", QUrl());
    QQuickItem* childItem = qobject_cast<QQuickItem*>(component.create());

    if (childItem == nullptr)
    {
        qCritical() << component.errorString();
        return 0;
    }

    // Set the text of the QML item. It's possible to set all the properties
    // with this way.
    childItem->setProperty("text", "Hello dynamic object");
    // Put it into the root QML item
    childItem->setParentItem(view.rootObject());

    // Display the window
    view.show();
    return app.exec();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM