3

Is possible to create a custom style file in QT and apply it for all QML files (like CSS does applies to HTML )?

Is there any "class" declaration for QML ?

Daniel Santos
  • 14,328
  • 21
  • 91
  • 174

1 Answers1

1

If you want to declare a "class" in QML you have to create new QML file. Its name must begin with a capital letter. You can also create custom objects using C++ but probably that is not what you are looking for.

Let's say you want to create custom Text element so the text is always centered and fits the given dimensions. So you create a file named CustomText.qml and write:

/* CustomText.qml file */    

import QtQuick 2.0

Text {
    id: customText
    horizontalAlignment: Text.AlignHCenter
    verticalAlignment: Text.AlignVCenter
    clip: true
    fontSizeMode: Text.Fit
    font.pixelSize: height
    wrapMode: Text.WordWrap
    minimumPixelSize: 3
    color: "black"

    /* using these lines you can set custom font loaded from a file */
//    font.family: customFont.name
//    FontLoader {
//        id: customFont
//        source: "qrc:/myCustomFont.ttf"
//    }
}

Now you can use it like this:

/* main.qml file */
import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    visible: true

    width: 300
    height: 300

    Rectangle {
        id: rectangle1
        color: "lightgrey"
        x: 5
        y: 5
        width: 200
        height: 50

        CustomText {
            anchors.fill: parent
            text: "testing custom text object"
        }
    }

    Rectangle {
        id: rectangle2
        color: "lightgrey"
        anchors.left: rectangle1.left
        anchors.top: rectangle1.bottom
        anchors.topMargin: 5
        width: 50
        height: 50

        CustomText {
            anchors.fill: parent
            text: "testing custom text object"
        }
    }

    Rectangle {
        id: rectangle3
        color: "lightgrey"
        anchors.left: rectangle2.left
        anchors.top: rectangle2.bottom
        anchors.topMargin: 5
        width: 100
        height: 100

        CustomText {
            anchors.fill: parent
            text: "testing custom text object"
        }
    }
}

That is how it would look like:

image showing example code in action

Filip Hazubski
  • 1,668
  • 1
  • 17
  • 33
  • what If, from now on, every element must use a Green font color.? must I create a custom QML for every element? I would like to take an existent project and, somehow, change it's style – Daniel Santos Dec 15 '15 at 12:31
  • 1
    @DanielSantos Unfortunately yes. You would have to manually change every `Text` to `CustomText` and in it set `color: "green"`. – Filip Hazubski Dec 15 '15 at 12:33