MusiGenesis
MusiGenesis

Reputation: 75296

How to create a custom grouping of properties and apply them to different controls?

I have a window with Buttons, TextFields, Labels etc. These all share common properties like font family, color, size etc. What I would like to be able to do is to define a grouping of these properties (called, say, textStyles.MainTitle or textStyles.DescriptiveText etc.) that would include a font family, size and weight, height and color. And then in the QML file I would write something like:

myCustomProperty: textStyles.MainTitle

and this would apply those values to the control. How can I do this?

Upvotes: 0

Views: 390

Answers (1)

dtech
dtech

Reputation: 49289

QML controls are styled by implementing their respective styles, for example for Button you have to implement a ButtonStyle.

As for the actual "grouping" you can just use a QtObject

property QtObject textStyles : QtObject {
    property FontLoader mainTitle : FontLoader {...}
    ....
}

You can also extend styled components as dedicated types:

// StyledText.qml

Text {
  font.family: someFont
  font.pixelSize: fontSize
  color: someColor
  font.italic: true
  font.letterSpacing: -1
  ...
}

And then use that by just StyledText {} instead of repeatedly styling regular Text elements.

Where / in what file do I place the QtObject snippet? I don't understand what // StyledText.qml is, or what a FontLoader is.

If you want it to be available in your entire application, you can put it as a property of your root object in main.qml, thanks to dynamic scoping textStyles will resolve from every other file in your project. You can put entire component styles in it as well and share in the project.

StyledText.qml is just an extra qml file you add to your project, you can being with just implementing its body in an existing qml file, then rightclick on Text and select refactoring -> move component into separate file.

A FontLoader is just a regular QML component, you can use it to load specific fonts and use as a font source for text. You don't have to use that, you can use font families from your system fonts as well. The font loader is useful for fonts you bundle with your application.

Upvotes: 1

Related Questions