从 C++ 向 QML 布局添加对象
Add objects to QML layout from C++
我如何从 C++ 中向 ID 为 root
的那个动态添加更多 Rectangle
?例如,另外两个 Rectangle
彩色 red
和 green
?
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++ 中这样做,那也是可能的。例如:
main.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();
}
main.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 是私有的,不推荐这种方式。
此外,请注意,我使用 objectName
从 C++ 访问项目,而不是 id
,因为它在 C++ 端不可见。
我如何从 C++ 中向 ID 为 root
的那个动态添加更多 Rectangle
?例如,另外两个 Rectangle
彩色 red
和 green
?
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++ 中这样做,那也是可能的。例如:
main.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();
}
main.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 是私有的,不推荐这种方式。
此外,请注意,我使用 objectName
从 C++ 访问项目,而不是 id
,因为它在 C++ 端不可见。