In QML I want to be able to define a set of font properties for simple semantic re-use. For example, instead of:
Text {
text: "This is a header"
font { family:'Encode Sans'; weight:Font.Black; italic:false; pointSize:24 }
}
I want to be able to write:
Text {
text: "This is a header"
font: headerFont
}
How can I make a single font
value that I can assign like this?
I know that I make a component, like:
# Header.qml
Text {
font { family:'Encode Sans'; weight:Font.Black; italic:false; pointSize:24 }
}
# main.qml
Header { text:"This is a header" }
However, this does not work for when I want to use the same font settings for a Label
or other place where a font
is needed.
I also know that I can use the answers to this question to, for example:
// style.js
.pragma library
var header = {
family: 'Encode Sans',
weight: Font.Black, // is this legal?
italic: false,
size: 24
};
// main.qml
import "style.js" as Style
Text {
text: "This is a header"
font {
family: Style.header.family
weight: Style.header.weight
italic: Style.header.italic
pointSize: Style.header.size
}
}
While this does single-source the values, it is, as shown, painfully verbose.
I tried this...
Font {
id: header
family: 'Encode Sans'
weight: Font.Black
italic: false
pointSize: 24
}
Text {
text: "This is a header"
font: header
}
...but it errors "Element is not creatable" on the Font {
line.
This answer covers exactly what I needed. I can use Qt.font()
method to create a font value with the properties I need. Wrapped in a QtObject with a global ID, I can then:
### main.qml
QtObject {
id: theme
property font headerFont: Qt.font({
family: 'Encode Sans',
weight: Font.Black,
italic: false,
pointSize: 24
})
}
### AnyOther.qml
Text {
text: "This is a header"
font: theme.headerFont
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With