【发布时间】:2023-03-07 09:36:01
【问题描述】:
- 如何从 C++ 代码中的任意位置检索根对象(下面的代码返回 0,
rootContext()->findChild()也返回 0)(其中类是已注册的 QML 类型且类组件定义是直接子级的类方法)的根,请参阅 objectName) 并在运行时添加生成的 QQuickItem? - 有 myclass 注册为 QML 类型。如何使用最底层的代码将 QML
Button添加到场景中?
在main.qml(片段)中
import QtQuick 2.3
import QtQuick.Window 2.2
Window {
objectName: root
visible: true
width: 360
height: 100
// ...
}
myclass.cpp
void myclass::add_hip()
{
setProperty("hip", 87);
QQmlEngine *engine = QtQml::qmlEngine(this);
// QObject *root = engine->rootContext()->findChild<QObject*>("womanObj");
QQuickWindow *window = qobject_cast<QQuickWindow *>(root);
QObject *wobj = window->findChild<QObject *>("womanObj");
// 1. Define a QML component.
QQmlComponent *readHipComp = new QQmlComponent(engine);
readHipComp->setData("import QtQuick.Controls 1.2\n\
Button {\n\
anchors.top: addHipBtn.top\n\
anchors.left: addHipBtn.left\n\
anchors.margins: 3\n\
text: \"Hip value\"\n\
onClicked: {\n\
msgDlg.text = myclass.hip\n\
msgDlg.open()\n\
}\
}", QUrl());
// 2. Create the component instance.
QQuickItem *readHipBtn = qobject_cast<QQuickItem *>(readHipComp->create());
// 3. Add the instance to the scene.
// readHipBtn->setParentItem(qobject_cast<QQuickItem *>(engine->rootContext()->contextObject()));
// QObject *root = QtQml::qmlContext(this)->findChild<QQuickItem *>("root");
// readHipBtn->setParent(root);
}
更新
extern QQuickWindow *window;
void myclass::add_hip()
{
//...
readHipBtn->setParentItem(window->contentItem());
//...
}
工作,但是 3.) 它没有看到其他 main.qml 对象。
【问题讨论】:
-
“任何地方”是什么意思? QML 中的任何地方? C++ 文件中除 main.cpp 之外的任何位置?