QML Form layout (GridLayout) troubles

折月煮酒 提交于 2019-11-29 07:38:47

The problem is that the Item containing your Button doesn't have a height set. This type of problem is the first thing to check when debugging layout problems. You can do so by printing out the geometry of the item:

Item {
    Layout.columnSpan: 2
    Layout.fillWidth: true

    Component.onCompleted: print(x, y, width, height)

    Button {
        anchors.centerIn: parent
        text: "Enter"
        onClicked: {
            loginWindow.close();
        }
    }
}

This outputs:

qml: 0 87 118 0

The fix:

Item {
    Layout.columnSpan: 2
    Layout.fillWidth: true
    implicitHeight: button.height

    Button {
        id: button
        anchors.centerIn: parent
        text: "Enter"
        onClicked: {
            loginWindow.close();
        }
    }
}

The complete code:

import QtQuick 2.2
import QtQuick.Window 2.0
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1

Window {
    id: loginWindow
    property string username: login.text;
    property string password: password.text;
    property bool issave: savePassword.checked;

    flags: Qt.Dialog
    modality: Qt.WindowModal
    width: 400
    height: 160
    minimumHeight: 160
    minimumWidth: 400
    title: "Login to program"

    GridLayout {
        columns: 2
        anchors.fill: parent
        anchors.margins: 10
        rowSpacing: 10
        columnSpacing: 10

        Label {
            text: "Login"
        }
        TextField {
            id: login
            text: "blah"
            Layout.fillWidth: true
        }

        Label {
            text: "Password"
        }
        TextField {
            id: password
            text: "blah"
            echoMode: TextInput.Password
            Layout.fillWidth: true
        }

        Label {
            text: "Save password?"
        }
        CheckBox {
            id: savePassword
        }

        Item {
            Layout.columnSpan: 2
            Layout.fillWidth: true
            implicitHeight: button.height

            Button {
                id: button
                anchors.centerIn: parent
                text: "Enter"
                onClicked: {
                    loginWindow.close();
                }
            }
        }
    }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!