【问题标题】:Get QML root object from anywhere in a code in Qt 5.3从 Qt 5.3 代码中的任何位置获取 QML 根对象
【发布时间】:2023-03-07 09:36:01
【问题描述】:
  1. 如何从 C++ 代码中的任意位置检索根对象(下面的代码返回 0,rootContext()->findChild() 也返回 0)(其中类是已注册的 QML 类型且类组件定义是直接子级的类方法)的根,请参阅 objectName) 并在运行时添加生成的 QQuickItem?
  2. 有 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 之外的任何位置?

标签: qt qml qt-quick qtquick2


【解决方案1】:

您不需要 objectName。

获取根元素并检查它是否是一个窗口:

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QObject *root = engine.rootObjects()[0];

QQuickWindow *window = qobject_cast<QQuickWindow *>(root);
if (!window) {
    qFatal("Error: Your root item has to be a window.");
    return -1;
}
window->show();

【讨论】:

  • 类是注册的QML类型且类组件定义在main.qml中的类方法如何访问根窗口?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多