本页内容

组件缺少必需属性

qmllint 将此警告类别拼写为[required] 。

组件缺少必填属性

发生了什么?

组件的必填属性未被设置。

这有什么问题?

在 QML 应用程序中,如果组件缺少必需属性,将会导致行为异常:如果静态检测到缺少必需属性,应用程序将完全无法启动。运行时,缺少必需属性的动态创建组件将无法被创建:它们将被设为 null。

示例

import QtQuick

Item {
    component RepeatMe: Item {
        required property int index;
        required property int helloWorld;
    }

    RepeatMe {} // not ok: required properties index and helloWorld not set

    Repeater {
        model: 10
        RepeatMe {} // not ok: required property index set by Repeater, but not helloWorld
    }
}

要解决此警告,请设置必需属性:

import QtQuick

Item {
    component RepeatMe: Item {
        required property int index;
        required property int helloWorld;
    }

    RepeatMe {
        index: 0
        helloWorld: 42
    } // ok: all required properties were set

    Repeater {
        model: 10
        RepeatMe {
            helloWorld: index * 2 + 1
        } // ok: all required properties were set: index by the Repeater and helloWorld by the user
    }
}

另请参阅 《QML 编码规范——必填属性》。

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