2

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?

jpnurmi
  • 5,716
  • 2
  • 21
  • 37
Luca
  • 10,458
  • 24
  • 107
  • 234

2 Answers2

2

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...

Florian Schmidt
  • 369
  • 3
  • 13
0

Yes, you just need to give an id to your TextField

TextField {
    id: myTextField
    ...
}

and reference the width of your TextField in your Button:

Button{
    ...
    width: myTextField.width
}
lolo
  • 706
  • 6
  • 19
  • Doing this just makes the two buttons overlap. There must be a better way to align them. Also, if you have spacing, this all gets very ugly. I tried `GridLayout` but no dice so far. – Luca Nov 03 '16 at 14:17