I have a QML Item
with some Text
fields in it, which should have all the same font. Do achieve this i introduce a new property myFont
of type font
. Do initialize this property I use the Qt.font
function, which creates a font object. But I have to specify at least one property (either family
or pointSize
).
My Question is now: How can I retrieve the default font for the myFont
property? If I create only a Text{}
item, it has already a default font attached, how can I get the same font for the myFont
property? (Meanwhile I use a hidden Text
field and create an alias to it's font
property, but I want a better solution).
Item {
property font myFont: Qt.font({pointSize: 10})
Text {
id: header
font: myFont
text: "My Header"
}
Text {
id: subject
font: myFont
text: "My Subject"
}
Text {
id: message
font: myFont
text: "Some meassage!"
}
}
I think the right way to solve this is to create your own object type with the font you need to use.
In the following example, the new object would be MyText.qml
. I don't know your whole code, but I suppose you have a ListView
with the delegate you posted in your question.
MyText.qml
import QtQuick 2.0
Text {
font: Qt.font({pointSize: 10})
}
main.qml
import QtQuick 2.5
import QtQuick.Window 2.2
Window {
visible: true
ListModel {
id: myModel
ListElement {
header: "header xxx"
subject: "subject xxx"
message: "message xxx"
}
ListElement {
header: "header yyy"
subject: "subject yyy"
message: "message yyy"
}
ListElement {
header: "header zzz"
subject: "subject zzz"
message: "message zzz"
}
}
ListView {
anchors.fill: parent
model: myModel
delegate: Item {
width: 300; height: 80
Column {
MyText {
id: myheader
text: header + " - family: " + font.family + " size: " + font.pointSize
}
MyText {
id: mysubject
text: subject + " - family: " + font.family + " size: " + font.pointSize
}
MyText {
id: mymessage
text: message + " - family: " + font.family + " size: " + font.pointSize
}
}
}
}
}
Now, I've digged into Qt source code. And it turns out that Qt uses a registered private TextSingleton which is defined (Qt 5.6) as:
pragma Singleton
import QtQuick 2.2
Text {
}
The font property of various qml controls is initialized:
font: TextSingleton.font
Digging further into C++ code reveals that for the Text
item, the font
property is a default initialized QFont
, which gives the QFont
object retrieved from QGuiApplication::font()
.
As I mentioned here , FontMetrics is the way to go since it's configurable and without using Qt.font(). You can declare it in your parent item or in a SIngleton type and the you can bind the property to it.
Here there's an example
Item {
id: root
FontMetrics {
id: fontMetrics
font.family: "Arial"
font.pixelSize: 24
}
property alias font: fontMetrics.font
Text { font: root.font }
Text { font: root.font }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.