本页内容

使用正确的函数

qmllint 将此警告类别拼写为[use-proper-function] 。

该属性是变体属性:它可能是一个方法,也可能不是

发生了什么?

您将类型为var 的属性当作可调用的函数来使用。

为什么这样不好?

这会影响代码的可读性;如果该属性不包含可调用函数,QML 引擎会报错;此外,QML 工具也无法应用特定的方法优化。

示例

import QtQuick

Item {
    property var fun: () => console.log("Hello")
    Component.onCompleted: { fun(); }
}

要解决此警告,请将 `fun ` 声明为函数以便能够调用它:

import QtQuick

Item {
    function fun() {
        console.log("Hello")
    }

    Component.onCompleted: { fun(); }
}

属性是 QJSValue 属性:它可能是一个方法,也可能不是

发生了什么?

您将类型为QJSValue 的属性当作可调用函数使用了。

注意: QJSValue 类型的属性 只能在 C++ 中定义。

为什么这样做不好?

该属性极有可能并非设计为可被调用,这将导致 QML 引擎在运行时报错。

示例

import QtQuick

Rectangle {
    // Rectangle has a property gradient of the type QJSValue
    Component.onCompleted: { console.log(gradient()); }
}

要修复此警告,请删除对 `gradient` 的调用:

import QtQuick

Item {
    // Rectangle has a property gradient of the type QJSValue
    Component.onCompleted: { console.log(gradient); }
}

或者,如果您是该属性的作者,可以考虑将属性定义替换为常规的Q_INVOKABLE 方法或槽。但这仅在该函数在 QML 中绝不会被修改的情况下才可行。如果您确实需要存储一个回调,那就没辙了。

信号被属性遮蔽

发生了什么?

您调用了被属性遮蔽的信号,或者您用属性遮蔽了信号。

这有什么问题?

调用者很可能期望调用的是信号,而不是被遮蔽的属性。这可能会导致 QML 引擎在运行时报错。

示例

import QtQuick

Item {
    component Base: Item {
        signal helloSignal
    }

    Base {
        property int helloSignal // shadows helloSignal inherited from Base
        Component.onCompleted: { helloSignal(); }
    }
}

要解决此警告,请重命名遮蔽属性:

import QtQuick

Item {
    component Base: Item {
        signal helloSignal
    }

    Base {
        property int helloSignal2 // does not shadow anymore
        Component.onCompleted: { helloSignal(); }
    }
}

方法被属性遮蔽

参见 {信号被属性遮蔽}。

插槽被属性遮蔽

参见 {信号被属性遮蔽}。

属性不是方法

发生了什么?

您将一个非var 或QJSValue 类型的属性当作可调用函数使用了。

为什么这样做不好?

该属性无法被调用,并将导致 QML 引擎在运行时报错。

示例

import QtQuick

Item {
    property int hello
    Component.onCompleted: { console.log(hello()); }
}

要解决此警告,请删除该调用,或将 `hello ` 改为函数:

import QtQuick

Item {
    property int hello
    Component.onCompleted: { console.log(hello); }

    // alternative:
    function helloAlternative() { ... }
    Component.onCompleted: { console.log(helloAlternative()); }
}

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