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 的模式:我们子类化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,versiondescription 是描述插件的元数据。

每个插件可以有一个或多个日志类别,用于按主题对警告进行分组。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.

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