Unsolved 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 }
-
@speqtr Thanks, this gets me closer to the solution. However setting font.pixelSize in an instance of MyField in the Row sets the correct field size, but the TextInput doesn't display the correct font (due to the alias?).
-
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 } }
-
This post is deleted! -
@speqtr When I said "TextInput doesn't display the correct font" I meant that the font used for the field was ignoring the font.pixelSize which was being set, although the spacing between the fields (based on the width/height) was correct.
-
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.