qmllint
qmllint是 Qt 附带的一个工具,用于验证 QML 文件的语法有效性。它还会对一些 QML 反模式发出警告。如果要禁用特定的警告类型,可在命令行中通过--help
找到相应的标志。
默认情况下,有些问题会导致警告被打印出来。如果警告数量超过限制(可通过--max-warnings
进行配置),退出代码将不会为零。qmllint 具有很强的可配置性,允许禁用警告或更改处理方式。用户可以自由地将任何问题转化为警告、信息或直接禁用。
qmllint 会发出以下警告
- 对属性的非限定访问
- 使用没有匹配信号的信号处理器
- 在 QML 中使用 with 语句
- 与编译 QML 代码有关的问题
- 未使用的导入
- 过时的组件和属性
- 以及许多其他问题
请参阅QML Lint Warning and Errors了解如何修复 qmllint 警告和错误。
注意: 为了让 qmllint 正常工作,它需要类型信息。这些信息由 QML 模块在导入路径中提供。默认情况下,当前目录以及 Qt 内置类型的导入路径被用作导入路径。要添加更多未包含在默认值中的导入路径,可通过-I
标志添加。
要获得所有可用命令行选项的概述和解释,请运行qmllint --help
。
编译器警告
qmllint 可以就qmlsc 无法编译的代码发出警告。
这些警告默认不启用。要启用它们,请指定--compiler warning
或相应调整设置文件。
将组件和属性标记为过时
qmllint 允许你将属性和组件标记为已废弃:
@Deprecated { reason: "Use NewCustomText instead" } Text { @Deprecated { reason: "Use newProperty instead" } property int oldProperty property int newProperty Component.onCompleted: console.log(oldProperty); // Warning: XY.qml:8:40: Property "oldProperty" is deprecated (Reason: Use newProperty instead) }
每次创建组件时,都会显示组件的废弃警告。
内联禁用警告
你可以在任何时候使用// qmllint disable
在文件中临时禁用警告。
当一行产生警告时,可以在行尾禁用警告:
Item { property string foo Item { property string bar: foo // qmllint disable unqualified } }
或者,你也可以禁用一个行块的注释,方法是将注释放在仅包含// qmllint disable
的行中,并以// qmllint enable
结束该行块:
Item { property string foo Item { // qmllint disable unqualified property string bar: foo property string bar2: foo // qmllint enable unqualified } }
qmllint 将以qmllint
开头的所有单行注释解释为指令。因此,除非您想启用或禁用警告,否则不能以这种方式开始注释。
注意: 如上面例子所示,最好明确指定要禁用的警告或警告列表,而不是禁用所有警告。只需在qmllint disable
后列出警告类别即可(名称与--help
中列出的选项相同)。
设置
除了传递命令行选项,你还可以通过设置文件配置 qmllint。命令行--write-defaults
会为你生成一个设置文件。
设置文件命名为.qmllint.ini
,看起来像这样:
[General] AdditionalQmlImportPaths= DisableDefaultImports=false OverwriteImportTypes= ResourcePath= [Warnings] BadSignalHandler=warning Deprecated=warning ImportFailure=warning InheritanceCycle=warning MultilineStrings=info PropertyAlias=warning RequiredProperty=warning TypeError=warning UnknownProperty=warning UnqualifiedAccess=warning UnusedImports=info WithStatement=warning
与命令行选项一样,警告级别也可以设置为info
、warning
或disable
。
qmllint 会自动在正在插入的 qml 文件位置查找设置文件。它还会在所有父目录中查找该文件,并自动应用其中的设置。您可以使用--ignore-settings
禁用此行为。您可以通过指定命令行参数来覆盖这些默认设置,这些参数优先于设置中的警告级别。
脚本
qmllint 可以通过--json <file>
选项写入或输出 JSON,该选项会返回包含警告信息、警告的文件和行位置及其严重程度的有效 JSON。使用特殊文件名"-"可写入 stdout 而不是文件。这样可以更轻松地将 qmllint 集成到预提交钩子或 CI 测试中。
另请参阅 类型描述文件和Qt Quick 工具和实用程序。
© 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.