Search code examples
qtqmlqtquick2qtquickcontrols

Align and size buttons to the textbox above it


I am using Qt qml to design a very simple user interface. The QML is as follows:

import QtQuick 2.0
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.4

Rectangle {
    width: 800; height: 600    

    ColumnLayout {
       anchors.centerIn: parent 
       spacing: 25

       TextField {
        placeholderText: qsTr("User name")
        width: 200
       }

        TextField {
         placeholderText: qsTr("Password")
         width: 200
         echoMode: TextInput.Password
        }

        RowLayout {
            Button {
                text: "Log In"
            }

            Button {
                text: "Cancel"
            }        
        }   
    }
}

What I am trying to do is ensure that both the buttons take the same size and they occupy the same amount of space horizontally as the TextField components. Is it possible to achieve this using QML?


Solution

  • Just resize the Layout to the wanted width and use the attached property Layout.fillWidth: true to expand / reduce the size of the Item. Just updated your example to illustrate:

    import QtQuick 2.0
    import QtQuick.Layouts 1.1
    import QtQuick.Controls 1.4
    
    Rectangle {
        width: 800; height: 600
    
        ColumnLayout {
            width: 200
            anchors.centerIn: parent
            spacing: 25
    
            TextField {
                placeholderText: qsTr("User name")
                Layout.fillWidth: true
            }
            TextField {
                placeholderText: qsTr("Password")
                Layout.fillWidth: true
                echoMode: TextInput.Password
            }
            RowLayout {
                Button {
                    text: "Log In"
                    Layout.fillWidth: true
                }
    
                Button {
                    text: "Cancel"
                    Layout.fillWidth: true
                }
            }
        }
    }
    

    PS: It's not needed in a child-layout where Layout.fillWidth and Layout.fillHeight is set by default.

    If you have any questions on that feel free to ask...