English Spanish Italian Magyar French [qt-devnet.developpez.com] Български
Table of Content
Styling in QML
QML provides several mechanisms for styling a UI. Below are three common approaches.
Approach 1: Custom Component
QML supports defining your own custom components [doc.qt.nokia.com]. Below, we create a custom component TitleText that we can use whenever our UI requires a title. If we want to change the appearance of all the titles in our UI, we can then just edit TitleText.qml, and the changes will apply wherever it is used.
- // TitleText.qml
- Text {
- horizontalAlignment: Text.AlignHCenter
- font.pixelSize: 50
- color: "green"
- }
- // in use
- TitleText {
- text: "Title 1"
- }
Approach 2: Style Object
In this approach we define a Style object that contains a collection of properties defining the style. This object is instantiated in the root component, so it is available throughout the application.
- // Style.qml
- QtObject {
- property int textSize: 20
- property color textColor: "green"
- }
- // root component
- Rectangle {
- ...
- Style { id: style }
- ...
- }
- // in use
- Text {
- font.pixelSize: style.textSize
- color: style.textColor
- text: "Hello World"
- }
Approach 3: Hybrid (Style Object + Custom Component)
In this approach, we have a Style object that is used by our custom component.
- // Style.qml
- QtObject {
- property int titleAlignment: Text.AlignHCenter
- property int titleFontSize: 50
- property color titleColor: "green"
- }
- // root component
- Rectangle {
- ...
- Style { id: style }
- ...
- }
- // TitleText.qml
- Text {
- horizontalAlignment: style.titleAlignment
- font.pixelSize: style.titleFontSize
- color: style.titleColor
- }
- // in use
- TitleText {
- text: "Title 1"
- }

