Qt QML Compiler

Qt QML Compiler 模块包含 QML 工具所需的共享功能,像 Qt Quick 编译器 and qmllint 。它还提供 QQmlSA 框架,可以用于扩展工具的内置分析能力。

使用模块

使用 Qt 模块的 C++ API 要求直接 (或透过其它依赖) 链接到模块库。几个构建工具对此有专用支持,包括 CMake and qmake .

构建采用 CMake

使用 find_package() 命令定位所需模块组件在 Qt6 包:

find_package(Qt6 REQUIRED COMPONENTS QmlCompiler)
target_link_libraries(mytarget PRIVATE Qt6::QmlCompiler)
					

更多细节,见 构建采用 CMake 概述。

采用 qmake 构建

要配置采用 qmake 构建模块,添加模块作为值为 QT 变量在工程的 .pro 文件:

QT += QmlCompiler
					

使用 QQmlSA 框架

Qt QML Compiler 模块提供 QQmlSA framework which provides tools for static analysis of QML code. These tools can help ensure syntactic validity and warn about QML anti-patterns. Adding static analysis to a QML program is done by writing plugins. They will run a collection of analysis passes over the elements and properties of the QML code. The passes can be registered with a PassManager which holds the passes and can be called to analyze an element and its children. A pass is a check for a certain rule or condition evaluated on elements or properties. If the condition is met, the pass can warn the user of an indentified issue in the code and maybe even suggest a fix. It is called a pass because the analysis performed on elements and properties happens by running a collection of passes on them in succesion. Each pass should be responsible for identifying one specific issue only. Combining a set of passes can perform more complex analysis and, together, form a plugin. Element passes are defined by two main components, namely shouldRun() and run() . When performing the analysis, the pass manager will execute the pass over every element it encounters while traversing the children of the root element. For each element, if shouldRun() evaluated on that element returns true then run() is executed on it. Passes on properties trigger on three different events, namely when the property is bound, when it is read, and when it is written to. These can be implemented by overriding the onBinding() , onRead() and onWrite() functions respectively. As the code grows, so does the number of elements and properties. Performing the static analysis passes on all of them can become expensive. That's why it is good to be granular when deciding which elements and properties to analyze. For elements, the shouldRun() is intended to be a cheap check to determine if run() , which performs the real computation, should be run. For properties, the selection is done when registering the passes with the manager. The registerPropertyPass() 函数接受 moduleName , typeName and propertyName strings as arguments. These are used to filter down the set of properties affected by the registered pass.

范例

The QML 静态分析教程 展示如何使用 QQmlSA 框架以创建自定义 qmllint pass.

参考