QML: Resize CheckBox

2019-07-13 18:21发布

问题:

I have ListView with my own delegate.

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

ItemDelegate
{
    height: 40

    Row
    {
        spacing: 10
        anchors.verticalCenter: parent.verticalCenter

        CheckBox
        {

        }
    }
}

The problem is that check boxes does not resize despite ItemDelegate's height.

I get this for height = 40:

I get this for height = 10:

I've tried playing with CheckBox'es width and height values - did not help.

Is it possible to make it smaller at all, without customizing it?

回答1:

You can, in theory, increase the size of the indicator, but it won't increase the size of the checkmark image:

CheckBox {
    text: "CheckBox"
    anchors.centerIn: parent
    checked: true

    indicator.width: 64
    indicator.height: 64
}

There are a couple of reasons why the image is not scaled. First of all, the checkmark would be blurry if it was upscaled. And more importantly, to retain best possible performance. Instead of calculating all the sizes relative to each other and that way creating huge amounts of bindings like Qt Quick Controls 1 did, Qt Quick Controls 2 bases its scalability instead on the automatic high-DPI scaling system introduced in Qt 5.6. You get simply a different @Nx image when running with scale factor N.



回答2:

I'm afraid you need to customize your checkbox to get a different size.

Example:

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQml 2.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Component {
        id: contactDelegate

        ItemDelegate
        {
            id: item
            width: 40
            height: 40

            CheckBox
            {
                id: control
                text: name

                indicator: Rectangle {
                    implicitWidth: item.width
                    implicitHeight: item.height
                    x: control.leftPadding
                    y: parent.height / 2 - height / 2
                    border.color: control.down ? "#dark" : "#grey"

                    Rectangle {
                        width: 25
                        height: 25
                        x: 7
                        y: 7
                        color: control.down ? "#dark" : "#grey"
                        visible: control.checked
                    }
                }
            }
        }
    }

    ListView {
        width: 180;
        height: 200;
        spacing: 10

        model: ContactModel {}
        delegate: contactDelegate
    }
}

By the way, the spacing property should be set in your ListView, not the delegate. Otherwise, it has no effect.