QML 静态分析 1 - 基本设置

本章介绍了 qmllint 扩展插件的基本结构,以及如何将其与 qmllint 配合使用。

要创建我们的插件,首先需要启用 QmlCompiler 模块:

find_package(Qt6 REQUIRED COMPONENTS QmlCompiler)

然后,我们创建一个插件,并将其与 QmlCompiler 模块关联。

qt_add_plugin(HelloWorldPlugin)

target_sources(HelloWorldPlugin
    PRIVATE
        helloplugin.h
        helloplugin.cpp
)

target_link_libraries(HelloWorldPlugin PRIVATE Qt::QmlCompiler)

实现遵循了通过插件扩展 Qt XML 的模式:我们继承了QQmlSA::LintPlugin 类,

class HelloWorldPlugin : public QObject, public QQmlSA::LintPlugin
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID QmlLintPluginInterface_iid FILE "plugin.json")
    Q_INTERFACES(QQmlSA::LintPlugin)

public:
    void registerPasses(QQmlSA::PassManager *manager, const QQmlSA::Element &rootElement) override;
};

该插件引用了一个plugin.json 文件,其中包含一些重要信息:

{
    "name": "HelloWorld",
    "author": "Qt Example",
    "description": "Demonstrates how to write a qmllint plugin",
    "version": "1.0",
    "loggingCategories": [
        {
            "name": "hello-world",
            "settingsName": "HelloWorld",
            "description": "Used to create test messages"
        }
    ]
}

name,author 、version 和description 是用于描述该插件的元数据。

每个插件可以有一个或多个日志类别,用于按主题对警告进行分组。loggingCategories 接受一个类别数组,每个类别由

  • name,该名称用于标识类别,并在 qmllint 中作为标志名称,
  • settingsName,用于在 qmllint.ini 中配置该类别
  • description,该字段应描述哪些类型的警告消息会被标记为该类别

在本例中,我们只有一个日志类别:hello-world 。对于每个类别,我们都需要在插件中创建一个LoggerWarningId 对象。

static constexpr QQmlSA::LoggerWarningId helloWorld { "Plugin.HelloWorld.hello-world" };

我们使用字符串字面量来构造该对象,其格式应为Plugin.<plugin name>.<category name> 。

最后,为了让我们的插件真正发挥作用,我们必须实现registerPasses 函数。

voidHelloWorldPlugin::registerPasses(QQmlSA::PassManager*manager, constQQmlSA::Element &rootElement)
{
    const boolpluginIsEnabled= manager->isCategoryEnabled(helloWorld);
    qDebug() << "Hello World plugin is" << (pluginIsEnabled ? "enabled" : "disabled");
   if(!pluginIsEnabled)
        return;// 如果插件已被禁用,则跳过注册
    // 稍后将在这里注册我们的通行证
}

我们检查该类别是否已启用,并通过 `qDebug` 输出一条指示其状态的诊断信息。请注意,由于尚未注册任何通行证,该插件目前尚未执行任何有用的操作。这将在本教程的下一部分中完成。

不过,我们现在已经可以验证插件是否被正确检测到了。使用以下命令进行检查:

qmllint -P /path/to/the/directory/containing/the/plugin --Plugin.HelloWorld.hello-world info test.qml

-P 选项指示 qmllint 在指定文件夹中查找插件。为避免与 Qt 内部类别发生冲突,插件类别的命名规则始终为:以“Plugin”开头,后跟一个点,接着是插件名称,再跟一个点,最后是类别名称。运行该命令后应输出Hello World Plugin is enabled 。

© 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.