harsszegi
harsszegi

Reputation: 379

QT5: Instantiate the same QML components multiple times

I want to create component templates, meaning that I define my own MyButton type in a separate QML file, and I also want to define several singleton instances, like:

Predefined.qml:
pragma Singleton
[...]

property MyButton quitButton : quitButtonItem 
MyButton {
    id: quitButtonItem
    text: qsTr("Quit")
    imagesource : "qrc:/icons/quit.png"
}

then use it as:

Predefined { id: predefined }

Rectangle {
    predefined.quitButton {
        onClicked: console.log ("quit pressed.");
        anchors.bottom : parent.bottom
        anchors.horizontalCenter : parent.horizontalCenter
    }
}

a.) I don't want to use Loaders for this -> overkill b.) Don't really want to define as my QML files as many components I want to clone (eg QuitButton.qml, BackButtonQml, etc.)

Any idea how to have it done? Thanks

Upvotes: 0

Views: 529

Answers (1)

GrecKo
GrecKo

Reputation: 7150

It can't be done.

The only way to instantiate an object declaratively from QML without a Loader is to create a new file for each component.

My suggestion for your usecase would simply be to create the files. Alternatively, it appears you are doing some sort of navigation bar. What about unifying this in a single component?

I see two ways: have a single global nav bar for all your app, for example in ApplicationWindow's header, or have a commonbase type like YourPage.qml where you implement your bar, and then simply inherit from it for your actual content. Personally, I adopted the first solution.

Upvotes: 1

Related Questions