QML как создавать разные типы на основе условия - PullRequest
0 голосов
/ 29 августа 2018

Мне было интересно, как лучше всего создать прямоугольник, текст или кнопку на основе условия внутри моего кода QML.

Вот псевдокод:

    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
        }
    }

Ответы [ 2 ]

0 голосов
/ 29 августа 2018

Вы можете использовать Loader как «derM» или «создать» все элементы и установить видимость:

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"
    }
}
0 голосов
/ 29 августа 2018

Попробуйте с Loader

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