本页内容

上下文属性

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`:

同时在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)
}

另请参阅《从 C++ 向 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.