Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define QML component inline and override a property?

I'm trying and failing at something seemingly simple: define a simple text formatting component inline, then instantiate it multiple times with different text. Here's the code

Item {
.
.
.
Component {
    id: favButtonLabelText
    Text {
        text: "Blah!"
        color: StyleSingleton.xNavPrimaryText
        font.family: StyleSingleton.xNavTextFont
        font.pointSize: 28
    }
}
.
.
.       
Loader { sourceComponent: favButtonLabelText; text: "Diameter" }

At the Loader line, the text property is invalid. Attempts to define a property or alias on the component are rejected with "Component objects cannot declare new properties".

The only example I find in the docs, shows overriding the x property of a Rectangle defined in an inline component. It seem to me overriding the text property of a Text element is analogous.

How can I do this?

like image 599
Steve Fallows Avatar asked Oct 27 '25 22:10

Steve Fallows


1 Answers

As of Qt 5.15, a new feature has been added: inline Components

As the name suggests, it allows to define an component inline, with the benefits of:

You can create an instance of the component, without the overhead of using a Loader.
You can use the component type in property declarations.
You can refer to the component in other files than the one it is defined in.

Item {
.
.
.
component FavButtonLabelText: Text {
     property int aCustomProp: 0

     text: "Blah!"
     color: StyleSingleton.xNavPrimaryText
     font.family: StyleSingleton.xNavTextFont
     font.pointSize: 28
}
.
.
.      
FavButtonLabelText { text: "myNewText"; aCustomProp: 5 }
like image 77
skaldesh Avatar answered Oct 29 '25 15:10

skaldesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!