Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML how to create different types based on a condition

Tags:

qt

qt5

qml

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
        }
    }
like image 622
bardao Avatar asked Jan 24 '26 20:01

bardao


1 Answers

Try it with a Loader

Loader {
    property bool shouldBeText
    Component { id: rect; Rectangle {}}
    Component { id: text; Text {}}
    sourceComponent: shouldBeText ? text : rect
}
like image 146
derM Avatar answered Jan 26 '26 21:01

derM