Trying to use FontMetrics in own Item
-
I have the following basic code in MyField.qml
TextInput { FontMetrics { id: fm font: parent.font } width: maximumLength * fm.averageCharacterWidth + 4 height: fm.height + 4 }
And in another file, I use this object, e.g.
Row { MyField { text: "Hello" font.bold: true } MyField { text:"World" }
But I always get the error "Unable to assign [undefined] to QFont"
How do I set the font within the FontMetrics to be the same font that has been selected for use by the user of MyField?
-
Try to use aliases:
TextInput { property alias font: fm.font FontMetrics { id: fm } width: maximumLength * fm.averageCharacterWidth + 4 height: fm.height + 4 }
-
I have the following basic code in MyField.qml
TextInput { FontMetrics { id: fm font: parent.font } width: maximumLength * fm.averageCharacterWidth + 4 height: fm.height + 4 }
And in another file, I use this object, e.g.
Row { MyField { text: "Hello" font.bold: true } MyField { text:"World" }
But I always get the error "Unable to assign [undefined] to QFont"
How do I set the font within the FontMetrics to be the same font that has been selected for use by the user of MyField?
After some more testing, I figured it out (I'm new to QML). I should have been using the onCompleted event to set the size after the font is fully initialised (in my particular case I don't want the width/height to be overridden).
TextInput { FontMetrics { id: fm } maximumLength: 10 selectByMouse: true Component.onCompleted: { fm.font = font width = (maximumLength + 1) * fm.averageCharacterWidth height = fm.height + 4 } }
-
Sorry for misunderstanding.
Can you try this one as a MyField?
TextInput { id: myField width: (maximumLength + 1) * fm.averageCharacterWidth height: fm.height + 4 maximumLength: 10 selectByMouse: true clip: true FontMetrics { id: fm font: myField.font } }
In this case setting font.pixelSize should work perfectly fine.
MyField { font.pixelSize: 14 }
Sorry for misleading you in a first place.