Narina
Narina

Reputation: 53

How to make the label size in QML according to the size of the text?

I can't make the height of the label exactly the height of the font, there is a gap at the bottom. Can you please tell me how to remove it? my label image

Label
{
  id: autoLabel
  leftInset: 0
  topInset: 0
  bottomInset: 0

  background: Rectangle
  {
    anchors.bottomMargin: 0
    color: "white"
    border.width: 0
  }

  Text
  {
    id: autoText
    anchors.fill: autoLabel
    anchors.leftMargin: 0
    anchors.topMargin: 0
    anchors.bottomMargin: 0
    color: PendulumStyle.primaryTextColor
    text: "AUTO"
    font.family: PendulumStyle.fontFamily
    font.pixelSize: 35
    font.styleName: "Bold"
    padding: 0
  }
  width: autoText.contentWidth
  height: autoText.contentHeight

  x: mainRectangle.x + 30
  y: checkBox.y - checkBox.height / 2
}

Upvotes: 1

Views: 2038

Answers (1)

JarMan
JarMan

Reputation: 8277

The Label actually IS the size of your font. The text you're using just doesn't show it. Fonts have a concept of an ascent and descent above and below the baseline.

Font structure

The ascent is the distance from the baseline to the top of the tallest character, and the descent is the distance from the baseline to the bottom of the lowest character. (Those might not be the technical definitions, but at least how I think of them. i.e. There may still be padding, etc.) So therefore, the total height of a font should be (ascent + descent).

In your case, you've used the word "AUTO". None of those characters go below the baseline. But the font height stays the same no matter what text you use.

If you still want your Rectangle to just fit around the word "AUTO", then it should just use the ascent height, and ignore the descent. To do that, QML provides a FontMetrics object that can help you.

    Label
    {
        id: autoLabel
        width: autoText.contentWidth
        height: fm.ascent

        FontMetrics {
            id: fm
            font: autoText.font
        }

        background: ...

        Text
        {
            id: autoText
            text: "AUTO"
            font.family: PendulumStyle.fontFamily
            font.pixelSize: 35
            font.styleName: "Bold"
        }
    }

Upvotes: 3

Related Questions