如何在 qml 中创建自定义本地模板对象?

How to create custom local template object in qml?

在我的 qml 文件中,我有很多统一的对象,几乎没有区别(例如 id)。

我想使用“不要重复自己”的原则

所以我想创建自定义本地模板,我可以在使用时附加独特的属性。

我知道创建单独的 .qml 文件,但是这个模板对于这种机制来说太小了(我似乎很想为带有 2px 边框的红色方块创建单独的 .qml 文件) qml有小模板的机制吗?

Qt 5.15.0 添加了对 inline components 的支持。这是文档中的示例:

import QtQuick 2.15

Item {
    component LabeledImage: Column {
        property alias source: image.source
        property alias caption: text.text

        Image {
            id: image
            width: 50
            height: 50
        }
        Text {
            id: text
            font.bold: true
        }
    }

    Row {
        LabeledImage {
            id: before
            source: "before.png"
            caption: "Before"
        }
        LabeledImage {
            id: after
            source: "after.png"
            caption: "After"
        }
    }
    property LabeledImage selectedImage: before
}