gpt4 book ai didi

qt - 从 C++ 将对象添加到 QML 布局

转载 作者:行者123 更新时间:2023-12-02 04:18:40 25 4
gpt4 key购买 nike

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

main.qml:

Rectangle {
id: root
}

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

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

Qt Creator 生成的 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++ 中做到这一点,那也是可能的。例如:

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,但 header 是私有(private)的,不推荐这样做。

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

关于qt - 从 C++ 将对象添加到 QML 布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31890372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com