Search code examples
qtqmlqqmlcomponent

How to create custom local template object in qml?


In my qml file i have a lot of uniform objects with few differencies (id for example).

I want to use "Don't Repeat Yourself" principle

So i want create custom local template, which i'll can append with unique properties on using.

I know about creating separate .qml file, but this templates are too small for this mechanism (It's seems wired for me to create separate .qml file for red squares with 2px border) Is there any meachanism for small templates in qml?


Solution

  • Qt 5.15.0 adds support for inline components. Here's the example from the docs:

    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
    }