Fausto01
Fausto01

Reputation: 211

Qt QML change item of a page dynamically

I have BasePage.qml like this:

Item {
    property alias content: loader.sourceComponent
    signal topBarLeftButtonClicked()

    TopBar {
    ...
    }

    Loader {
        id: loader
    }

    BottomBar {
    ...
    }
}

This way I can change dynamically the content of the page, but I must use Component, and I can't read properties of the content in a DerivedPage.
For example:

DerivedPage.qml

BasePage {
    onTopBarLeftIconClicked: item.text //error, item is not defined

    content: Component {
        TextField {
            id: item
        }
    }
}

Any solution?

Upvotes: 1

Views: 776

Answers (2)

Fausto01
Fausto01

Reputation: 211

I found a way to replace loader and components:

//BasePage.qml
Item {
    default property alias data: item.data
    signal topBarLeftButtonClicked()

    TopBar {
    ...
    }

    Item{
        id: item
    }

    BottomBar {
    ...
    }
}

//DerivedPage.qml
BasePage {
    onTopBarLeftIconClicked: textField.text = "string"

    TextField {
        anchors.fill: parent
        id: textField
    }
}

This way textField replace item in BasePage.qml

Upvotes: 0

Andrii
Andrii

Reputation: 1906

You can define an alias to the Loader's item property inside BasePage, like that:

property alias contentItem: loader.item

And refer to it instead of content item within DerivedPage.


Putting it all together:

// BasePage.qml
Item {
    property alias content: loader.sourceComponent
    property alias contentItem: loader.item
    signal topBarLeftButtonClicked()
    Loader { id: loader }
}

// DerivedPage.qml
BasePage {
    onTopBarLeftIconClicked: { contentItem.text = "clicked" }
    content: Component { TextField { } }
}

Upvotes: 2

Related Questions