5

For example i have 2 different QML elemnts with common property such as:

import QtQuick 2.0

Rectangle {
    width: 360
    height: 360

    Text {
        id: t
        color: "red"
        text: qsTr("Hello World")
        anchors.top: parent.top
    }
    TextInput {
        text: qsTr("Hello all!")
        color: "red"
        anchors.top: t.bottom

    }
}

You can see, that Text and TextInput have equal property called "color" with equal value.

In QSS i can use common property value, for example:

QWidget {
   background: "red"
}

and all QWidgets, that belong the qss widget also will have red background.

Is way for set common property in QML?

1 Answer 1

10

There is no support for customizing using QSS in QML. But you can use "Style Object" method to set the properties and use them in all your QML files.

In this, you define a Style object in a "Style.qml" file, with properties defining the style. Instantiate in the root component, so it will be 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"
}

You can find more information here.

2
  • It's not immediately obvious but Rectangle gets the properties of QtObject by inheritance.
    – Jay
    Jul 26, 2013 at 15:20
  • 1
    @Jay, what's happening here isn't any QtObject inheritance magic. The Style object can just as easily be an Item or a Rectangle. What makes this work is that the Style object is placed in the root where the child tree has access to it.
    – MrEricSir
    Oct 1, 2013 at 5:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.