将 C++ 中的状态暴露给 QML
通常,我们希望将某些属性从 C++ 暴露给特定组件中的所有 QML 元素、模块中的所有 QML 元素,甚至所有 QML 元素。您可以通过引入单例或向选定组件的根对象添加属性来实现这一点。
使用单例
若要将若干全局属性暴露给模块中的所有元素或所有元素,可以在 C++ 中定义一个单例。为此,请在包含要作为 `Q_PROPERTY ` 声明进行暴露的属性的类中,添加 `QML_ELEMENT ` 或 `QML_NAMED_ELEMENT ` 宏以及 `QML_SINGLETON` 宏:
// 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 代码中访问该单例的thing属性:
import QtQml
QtObject {
objectName: "The thing is " + Singleton.thing
}如果您将 QML 文件放置在与模块相同的目录下(强烈建议这样做),则可以通过模块内的隐式导入访问该单例。您无需显式导入任何内容。否则,或者如果您希望从其他模块访问thing属性,则需要显式导入该单例所属的模块。
若要在 C++ 中设置该属性的值,您可能需要获取单例实例。为此,您可以使用 `QQmlEngine::singletonInstance`。推荐的做法是将模块名和类型名作为参数传入:
Singleton *singleton
= engine->singletonInstance<Singleton *>("MyModule", "Singleton");
singleton->setThing(77);使用对象属性
若您希望仅向特定组件中的 QML 元素暴露某些属性,可将其作为常规属性添加到该组件的根对象上。为确保这些属性在所有情况下均被有效设置,可将其设为“必填属性”。您的 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 导入路径中。
© 2026 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.