上下文属性
此警告类别由 qmllint 拼写[context-properties] 。
检测到潜在的上下文属性访问
发生了什么事?
检测到潜在的上下文属性访问。
为什么会这样?
通过在您的 QML 代码中使用上下文属性,您创建了一个从您的 QML 代码到您编写代码时所想到的特定上下文的依赖关系。这就限制了代码的可重用性,因为在其他可能使用它的地方,上下文可能是不同的。此外,这种依赖关系没有声明。您从未导入上下文或以其他方式说明您的期望。因此,任何试图重用你的代码的人都很难发现,重用你代码的地方是否有足够的上下文。
QML 工具不能使用上下文属性:编译器不能把这个文件编译成 C++,qmllint以及 QML Language Server不能对该文件提供有用的警告。
示例
// main.cpp int main(int argc, char **argv) { QGuiApplication app(argc, argv); QQuickView view; view.rootContext() ->setContextProperty("myProperty", QDateTime::currentDateTime()); view.loadFromModule("MyModule", "Main"); view.show(); app.exec(); }
// Main.qml import QtQuick Item { Component.onCompleted: console.log(myProperty) }
要修复此警告,您可以
- 将该属性设置为必填属性。
- 使用单例。
- 在
.contextProperties.ini中添加一个条目。
使用必填属性
对于在不同组件中具有不同值的上下文属性,请使用必填属性。要使用必填属性修复此警告,请使用setInitialProperties 方法之一,而不是setContextProperty :
- QQuickView::setInitialProperties,
- QQmlComponent::setInitialProperties,
- QQmlApplicationEngine::setInitialProperties,
- QQmlIncubator::setInitialProperties或
- QQuickWidget::setInitialProperties.
也可在Main.qml 中定义所需的属性。
// main.cpp int main(int argc, char **argv) { QGuiApplication app(argc, argv); QQuickView view; view.setInitialProperties( { {"myProperty", QDateTime::currentDateTime()} } ); view.loadFromModule("MyModule", "Main"); view.show(); app.exec(); }
// Main.qml import QtQuick Item { required property date myProperty Component.onCompleted: console.log(myProperty) }
另请参阅从 C++ 向 QML 公开状态。
使用单例
对于在所有组件中都有相同值的上下文属性,请使用单例。要使用单例解决此警告,请移除setContextProperty 调用,定义单例并用单例属性替换上下文属性用法。
// mysingleton.h class MySingleton : public QObject { Q_OBJECT QML_SINGLETON QML_ELEMENT Q_PROPERTY(QDateTime myProperty MEMBER m_myProperty NOTIFY myPropertyChanged FINAL) QDateTime m_myProperty = QDateTime::currentDateTime(); signals: void myPropertyChanged(); }; // main.cpp int main(int argc, char **argv) { QGuiApplication app(argc, argv); QQuickView view; view.loadFromModule("MyModule", "Main"); view.show(); app.exec(); }
// Main.qml import QtQuick Item { Component.onCompleted: console.log(MySingleton.myProperty) }
另请参阅Exposing State from C++ to QML。
在 .contextProperties.ini 中添加条目
如果无法替换上下文属性,可在项目源代码目录下创建.contextProperties.ini文件(如果没有),并写入以下内容:
[General] disableUnqualifiedAccess = "myProperty" warnOnUsage = "myProperty" disableHeuristic = false
如果.contextProperties.ini 文件已存在,要消除此警告,请将上下文属性名称追加到已存在的列表中:
[General] disableUnqualifiedAccess = "someOtherProperty,myProperty" warnOnUsage = "someOtherProperty,myProperty" disableHeuristic = false
有关.contextProperties.ini 格式的更多信息,另请参阅上下文属性设置。
© 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.