从 C++ 向 QML 公开状态
从 C++ 向特定组件中的所有 QML 元素、模块中的所有 QML 元素、甚至整体上的所有 QML 元素公开某些属性,通常是很理想的。您可以通过引入单子或在选定组件的根对象中添加属性来做到这一点。
使用单子
如果你想把一些全局属性公开给模块中的所有元素或所有元素,你可以用 C++ 定义一个单例。为此,请将QML_ELEMENT 或QML_NAMED_ELEMENT 宏和QML_SINGLETON 宏添加到包含要公开的属性的类中,作为Q_PROPERTY 声明:
// Singleton.h class Singleton : public QObject { Q_OBJECT Q_PROPERTY(int thing READ thing WRITE setThing NOTIFY thingChanged FINAL) QML_ELEMENT QML_SINGLETON public: Singleton(QObject *parent = nullptr) : QObject(parent) {} int thing() const { return m_value; } void setThing(int v) { if (v != m_value) { m_value = v; emit thingChanged(); } } signals: void thingChanged(); private: int m_value = 12; };
现在,你可以从任何导入该模块的 QML 代码中访问单例的事物属性:
import QtQml QtObject { objectName: "The thing is " + Singleton.thing }
如果你把 QML 文件放在与模块相同的目录下(强烈建议),那么单例就可以通过模块中的隐式导入获得。你不需要显式导入任何东西。如果没有,或者您想从其他模块访问该属性,则需要导入单例所属的模块。
为了从 C++ 中设置属性值,您可能需要检索单例。为此,您可以使用QQmlEngine::singletonInstance 。首选方法是将模块和类型名称作为参数:
Singleton *singleton = engine->singletonInstance<Singleton *>("MyModule", "Singleton"); singleton->setThing(77);
使用对象属性
如果你想只向特定组件中的 QML 元素公开一些属性,你可以把它们作为常规属性添加到组件的根对象中。为了确保它们在所有情况下都被设置,你可以把它们设置为必填属性(Required Properties)。您可以如下编写 QML 组件:
pragma ComponentBehavior: Bound import QtQuick Window { id: root visible: true required property int thing Text { anchors.fill: parent text: "The thing is " + root.thing } component Inner: QtObject { objectName: "I can see " + root.thing + " because I'm bound." } }
我们为组件的根元素使用一个 ID,并通过 ID 和名称从任何内部对象引用属性。为了使任何嵌套组件都能安全地使用根元素的 ID,我们使用了ComponentBehavior。
然后,在 C++ 中,当你从这样一个组件创建一个对象时,你需要确保调用QQmlComponent::createWithInitialProperties,QQmlApplicationEngine::setInitialProperties, 或QQuickView::setInitialProperties 来初始化属性。例如
QQmlEngine engine; QQmlComponent component(&engine, "MyModule", "RequiredProperties"); QScopedPointer<QObject> o(component.createWithInitialProperties({ {"thing", 11} }));
假设你的模块 URI 是MyModule,并且模块在 QML 导入路径中可用。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.