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, と はプラグインを説明するメタデータです。version description

各プラグインは、警告をテーマ別にグループ化するために使用される、1つ以上のロギング・カテゴリーを持つことができます。loggingCategories はカテゴリーの配列を取ります。

  • nameこれはカテゴリを識別するために使われ、qmllintのフラグ名として使われます、
  • settingsNameqmllint.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.