bardao
bardao

Reputation: 954

QML how to create different types based on a condition

I was wondering what's the best way to create a Rectangle, Text or Button based on a condition inside my QML code.

Here's a pseudo code:

    import QtQuick 2.0

    Item{
        property string name = "rect" or "text" or "button"
        id:root

        if (name === "rect")
        Rectangle {
            //properties
            parent: root
        }

        else if (name === "text")
        Text {
            //properties
            parent: root
        }

        else if (name === "button")
        Button {
            //properties
            parent: root
        }
    }

Upvotes: 2

Views: 3702

Answers (2)

hmuelner
hmuelner

Reputation: 8231

You can use a Loader like "derM" answered, or you "create" all Items and set the visibility:

Item{
    property string name = "rect" or "text" or "button"
    id:root

    Rectangle {
        //properties
        visible: root.name === "rect"
    }

    Text {
        //properties
        visible: root.name === "text"
    }

    Button {
        //properties
        visible: root.name === "button"
    }
}

Upvotes: 0

derM
derM

Reputation: 13701

Try it with a Loader

Loader {
    property bool shouldBeText
    Component { id: rect; Rectangle {}}
    Component { id: text; Text {}}
    sourceComponent: shouldBeText ? text : rect
}

Upvotes: 8

Related Questions