marco
marco

Reputation: 1752

QML: show only certain Components depending on a State

I have several ui.qml files, let's say A.ui.qml, B.ui.qml, C.ui.qml.

Then I have to create, depending on a State, a window that shows A+B, or B+A, or B+C, etc.

In my main.qml, I've actually written the following:

...
Item {
    id: contentArea
    state: "state1"

    AForm {
        id: aForm
    }

    BForm {
        id: bForm
    }

    states: [
        State {
            name: "state1"
            PropertyChanges { target: aForm; x: 0 }
            PropertyChanges { target: bForm; x: 400 }
        },
        State {
            name: "state2"
            PropertyChanges { target: aForm; x: 400 }
            PropertyChanges { target: bForm; x: 0 }
        }            
    ]
...

So, when setting contentArea.state = "state2", A and B forms are swapped.

But this is just an example to see if it works.

Now I need to create all the forms (I guess using Component) and show them only if the state is a certain one.

How to do that?

Upvotes: 1

Views: 631

Answers (1)

derM
derM

Reputation: 13701

You replace AForm and BForm by Loaders, and set the source-property of this Loaders to the right file name, or the sourceComponent to the right Component id.

Loader {
    id: topLoader
}
Loader {
    id: bottomLoader
    y: 200
}

states: [
    State {
        name: "state1"
        PropertyChanges { target: topLoader; source: "AForm.ui.qml" }
        PropertyChanges { target: bottomLoader; source: "BForm.ui.qml" }
    },
    ...
]

This process will destroy and recreate the instances of the ui.qml-files whenever the state changes.

You can also use e.g. a ListView with snapMode: ListView.SnapToItem, interactive: false, and change the currentItem when the state changes.

You could also create all the objects, and only parent the two you want to show to Items that serve as frames, and the rest is parented to null.

Or you use three or four Loaders of which you only show two, that you shift around as necessary, only loading files that shall be shown. Here you will need to write a bit more logic.

Upvotes: 1

Related Questions