English Spanish Italian Magyar French [qt-devnet.developpez.com] Български

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.

  1. // TitleText.qml
  2. Text {
  3.     horizontalAlignment: Text.AlignHCenter
  4.     font.pixelSize: 50
  5.     color: "green"
  6. }
  7.  
  8. // in use
  9. TitleText {
  10.     text: "Title 1"
  11. }

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.

  1. // Style.qml
  2. QtObject {
  3.     property int textSize: 20
  4.     property color textColor: "green"
  5. }
  6.  
  7. // root component
  8. Rectangle {
  9.     ...
  10.     Style { id: style }
  11.     ...
  12. }
  13.  
  14. // in use
  15. Text {
  16.     font.pixelSize: style.textSize
  17.     color: style.textColor
  18.     text: "Hello World"
  19. }

Approach 3: Hybrid (Style Object + Custom Component)

In this approach, we have a Style object that is used by our custom component.

  1. // Style.qml
  2. QtObject {
  3.     property int titleAlignment: Text.AlignHCenter
  4.     property int titleFontSize: 50
  5.     property color titleColor: "green"
  6. }
  7.  
  8. // root component
  9. Rectangle {
  10.     ...
  11.     Style { id: style }
  12.     ...
  13. }
  14.  
  15. // TitleText.qml
  16. Text {
  17.     horizontalAlignment: style.titleAlignment
  18.     font.pixelSize: style.titleFontSize
  19.     color: style.titleColor
  20. }
  21.  
  22. // in use
  23. TitleText {
  24.     text: "Title 1"
  25. }

Categories: