How to make image to fill qml controls button

lnk picture lnk · Dec 5, 2014 · Viewed 19.3k times · Source

I want icon to fill Button. Here is code:

import QtQuick 2.3
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
import QtQuick.Window 2.2

Window{
    id: root
    title: "settings"
    flags: Qt.Dialog
    minimumHeight: 700
    minimumWidth: 700
    maximumHeight: 700
    maximumWidth: 700

    ColumnLayout{
        id: columnLayout
        anchors.fill: parent
        RowLayout{
            Button{
                iconSource: "images/1x1.png"
                checkable: true
                checked: true
                Layout.minimumWidth: 100
                Layout.minimumHeight: 100
                }

            Button{
                iconSource: "images/1x2.png"
                checkable: true
                checked: false
                Layout.minimumWidth: 100
                Layout.minimumHeight: 100
            }
            Button{
                iconSource: "images/2x1.png"
                checkable: true
                checked: false
                Layout.minimumWidth: 100
                Layout.minimumHeight: 100
            }
            Button{
                iconSource: "images/2x2.png"
                checkable: true
                checked: false
                Layout.minimumWidth: 100
                Layout.minimumHeight: 100
            }
        }
        Rectangle{
            visible: true
            implicitHeight: 600
            implicitWidth: 700
            color: "red"
        }
    }
}

Button size is 100*100 pixels but image size is much lower. How to make image to be as big as button

Answer

BaCaRoZzo picture BaCaRoZzo · Dec 7, 2014

It really depends on what you want to achieve. IMO, there are three solutions here:

1) If you need an image as a button, just use Image with a MouseArea filling it:

Image {
    source: "http://images5.fanpop.com/image/photos/27500000/Cool-beans-azkaban-27533920-200-200.gif"

    MouseArea {
        anchors.fill: parent
        onClicked: {
           console.info("image clicked!")
        }
    }
}

2) If you want to use a button with an image, redefine the label property of the style, as follows:

Button{
    width: 200
    height: 200

    style: ButtonStyle {

        label: Image {
            source: "http://images5.fanpop.com/image/photos/27500000/Cool-beans-azkaban-27533920-200-200.gif"
            fillMode: Image.PreserveAspectFit  // ensure it fits
        }
    }
}

This way you can fit any image in the Button and the small padding to the borders allows you to see when the button is clicked/checked. Mind that, by using ButtonStyle, you lose the platform style.

3) If you really want to use the Button and make it look like an Image follow the smart approach proposed by Mitch.