Search code examples
c++qtqml

How to inflate Label's background rect


How do I draw a background rectangle around Label?

Here's what I do

import QtQuick 2.0
import QtQuick.Controls 2.15

Label {
    id: label
    text: root.text
    font {
        pointSize: 24
        bold: true
    }
    wrapMode: Text.WordWrap
    background: Rectangle{
        radius: 20
        color: "lightgreen"
        anchors.centerIn: parent
        width: parent.width + 30
        height: parent.height + 30
    }
}

And that sure draws a rounded rect around Label, but the size of the label stays the same, so the layout can't position it right. How do I make it work?


Solution

  • I think what you're looking for is padding. Don't add anything to the height/width of the background. Just add padding.

    Label {
        id: label
        text: root.text
        font {
            pointSize: 24
            bold: true
        }
        wrapMode: Text.WordWrap
        padding: 15
        background: Rectangle{
            radius: 20
            color: "lightgreen"
            width: parent.width
            height: parent.height
        }
    }