Qt - 如何从C ++类动态插入Qml对象

时间:2017-06-06 19:03:11

标签: c++ qt qml qtquickcontrols qqmlcontext

我需要一个关于我的简单 QT / QML 应用程序的建议。

我有以下情况:

关于界面,我有一个名为'flickableArea'的主区域(flickableArea.qml)分为四个区域(项目 slot1 ,项目 slot2 ,项目 slot3 和项目 slot4 )。

每个插槽都填充了QML Rectangle对象。

slot1 由矩形填充,其中id = area1 slot2 由矩形填充,其中id = area2 ,< strong> slot3 由矩形填充,其中id = area3 slot4 由矩形填充,其中id = area4

文件 flickableArea.qml

import QtQuick 2.4
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.4

Item {

    property alias mainGrid: mainGrid
    property alias slot1: slot1
    property alias slot2: slot2
    property alias slot3: slot3
    property alias slot4: slot4

    id: flickableAreaItem
    width: 600
    height: 300

    Flickable {
        id: flickableArea
        boundsBehavior: Flickable.DragOverBounds
        interactive: true
        flickableDirection: Flickable.HorizontalFlick
        anchors.fill: parent

        GridLayout {
            id: mainGrid
            columnSpacing: 3
            rowSpacing: 3
            rows: 2
            columns: 2
            anchors.fill: parent

            Item {
                id: slot1
                Layout.fillWidth: true
                Layout.fillHeight: true
                clip: false
                Rectangle {
                    anchors.fill: parent
                    border.width: 1
                    border.color: "black"
                }
            }

            Item {
                id: slot2
                Layout.fillWidth: true
                Layout.fillHeight: true
                clip: false
                Rectangle {
                    anchors.fill: parent
                    border.width: 1
                    border.color: "black"
                }
            }

            Item {
                id: slot3
                Layout.fillWidth: true
                Layout.fillHeight: true
                clip: false
                Rectangle {
                    anchors.fill: parent
                    border.width: 1
                    border.color: "black"
                }
            }

            Item {
                id: slot4
                Layout.fillWidth: true
                Layout.fillHeight: true
                clip: false
                Rectangle {
                    anchors.fill: parent
                    border.width: 1
                    border.color: "black"
                }
            }

        }
    }
}

当定义的信号出现时,我应该在 area1 area2 area3 area4 中动态插入QML对象在c ++代码中触发。 在c ++代码中,当触发信号时,我运行以下代码来创建一个连接到Object.qml的新对象(ObjectToIntroduce):

ObjectToIntroduce *obj;
obj = new ObjectToIntroduce();
QQmlContext *objContext = engine->rootContext();
objContext->setContextProperty("obj", obj);

在我创建了一个新的ObjectToIntroduce后,如何在flickableArea.qml的area1 / area2 / area3 / area4中引入/销毁(查看/隐藏)Object.qml?

我想知道实现这种机制的最佳方法是什么,编写这个简单的Qt / Qml应用程序。 感谢您的建议,最好的问候

乐乐

0 个答案:

没有答案