从 C++ 向 QML 布局添加对象 [英] Add objects to QML layout from C++

查看:41
本文介绍了从 C++ 向 QML 布局添加对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何从 C++ 中动态添加更多 Rectangle 到 id root 的矩形?例如,另外两个 Rectangle 的颜色为 redgreen?

How can I, from the C++, add some more Rectangles dynamically to the one with id root? For example, two more Rectangles colored red and green?

main.qml:

Rectangle {
    id: root
}

要在root"下添加的典型 QML 对象:

Typical QML objects to add under 'root':

Rectangle { color: "red"; width: 200; height: 200 }
Rectangle { color: "green"; width: 200; height: 200 }

Qt Creator 生成的main.cpp:

Qt Creator generated main.cpp:

int main(int argc, char *argv[]) { 
    QGuiApplication app(argc, argv);
    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile(QStringLiteral("qml/gui/main.qml"));
    viewer.showExpanded();    
    return app.exec()
}

推荐答案

创建动态项目的最佳方式是 QML 本身.但是如果你仍然想在 C++ 中做到这一点,那也是可能的.例如:

The best way to create dynamic items is QML itself. But if you still want to do that in C++ it's also possible. For example:

ma​​in.cpp:

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQuickView view;
    view.setSource(QUrl("qrc:/main.qml"));
    view.show();
    QObject *root = view.rootObject();
    QQuickItem * myRect = root->findChild<QQuickItem *>("myRect");
    if(myRect) {
        QQmlComponent rect1(view.engine(),myRect);
        rect1.setData("import QtQuick 2.4; Rectangle { width:100; height: 100; color: \"orange\"; anchors.centerIn:parent; }",view.source());
        QQuickItem *rect1Instance = qobject_cast<QQuickItem *>(rect1.create());
        view.engine()->setObjectOwnership(rect1Instance,QQmlEngine::JavaScriptOwnership);
        if(rect1Instance)
            rect1Instance->setParentItem(myRect);
    }
    return app.exec();
}

ma​​in.qml

import QtQuick 2.4

Item {
    width: 600
    height: 600

    Rectangle {
        objectName: "myRect"
        width: 200
        height: 200
        anchors.centerIn: parent
        color:  "green"
    }
}

由于所有 QML 项都有相应的 С++ 类,因此可以直接创建 QQuickRectangle,但标头是私有的,不推荐这种方式.

Since all QML items have corresponding С++ classes it's possible to create QQuickRectangle directly but the header is private and that isn't recommended way.

另外,请注意,我使用 objectName 从 C++ 访问 item,而不是 id,因为它从 C++ 端不可见.

Also, pay attention, I used objectName to access item from C++, not the id since it is not visible from C++ side.

这篇关于从 C++ 向 QML 布局添加对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆