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 ?
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: