Luca
Luca

Reputation: 11016

QML: button with image and text underneath

I am trying to create a button like control in QML which displays an image and also some text under it. My current attempt stands as follows:

  Item {
        id: button
        width: 30
        height: 100
        property alias text: buttontext
        signal clicked

        Image {
            id: visualImage
            anchors.fill: parent
            source: "qrc:/images/test.png"
        }

        Text {
            id: buttontext
            font.bold: true
            text: "Test"
        }
    }

This has a lot of problems unfortunately. So, at the moment, I am specifying the width and height of the item but this should be calculated based on the width and height of the image and the text. Also, the text is shown at the top and inside the image where I would like to position the text under the image, centered with image horizontally with some margins.

Upvotes: 3

Views: 9909

Answers (3)

bam
bam

Reputation: 194

Since QtQuick.Controls 2.3 (Qt 5.10), display property was introduced:

This property determines how the icon and text are displayed within the button.

For your case it's AbstractButton.TextUnderIcon

Upvotes: 2

Fabio
Fabio

Reputation: 2602

You must use anchors in the Image and in the Text. Example:

Item {
        id: button
        width: 30
        height: 100
        property alias text: buttontext
        signal clicked

        Image {
            id: visualImage
            anchors.top: parent.top
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.bottom: buttontext.top
            source: "qrc:/images/test.png"
        }

        Text {
            id: buttontext
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.bottom: parent.bottom
            font.bold: true
            text: "Test"
        }
    }

Upvotes: 3

Ldweller
Ldweller

Reputation: 337

Something I have done in the past as a workaround for this,

create a Rectangle{……} which holds all the 'Button' items, (Text/Image Ect),

It may not be the prettiest way but there is a few variations

  1. Create the 'Image' and 'text' externally (photoshop whatever you choose) then fill your Rectangle with the content, then also set a MouseArea { onClicked {……}} event to that,

  2. Make a Column/Grid/Row within the Rectangle and position your items using that method

Upvotes: 0

Related Questions