Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QFormLayout equivalent in QtQuick2?

I am in the process of porting a application based on QtWidgets over to QtQuick2.

I am trying to figure out what QtQuick layout items I should use.

I am stuck at QFormLayout. I simply cannot find an equivalent. The best I could find is a GridLayout, but I want the labels to be generated automatically (like in QFormLayout).

QHBoxLayout converts to RowLayout
QVBoxLayout converts to ColumnLayout
QGridLayout converts to GridLayout
QFormLayout converts to ???

like image 789
feedc0de Avatar asked Feb 15 '26 19:02

feedc0de


1 Answers

If you are satisfied with the GridLayout, only missing the automatic label generation, you can create yourself some small helper class, in which you encapsulate the Label and hold a property for the control.

// FormControl.qml

import QtQuick 2.0
import QtQuick.Controls 2.0

Item {
    id: root
    property alias label: myLabel

    Label {
        id: myLabel
        parent: root.parent

        Layout.fillHeight: true
        Layout.fillWidth: true

        verticalAlignment: Qt.AlignVCenter

        MouseArea {
            anchors.fill: parent
            onClicked: root.control.forceActiveFocus()
        }
    }

    property Item control

    Row {
        id: content
        parent: myLabel.parent // parent it to myLabel.parent, to make sure, that one is added first.
        children: [control]
    }
}

The usage is simple:

import QtQuick 2.7
import QtQuick.Layouts 1.1
import QtQuick.Controls 2.0

ApplicationWindow {
    id: myWindow
    visible: true
    width: 600
    height: 600
    color: 'white'

    GridLayout {
        columns: 2

        FormControl {
            label.text: 'test1'
            control: ComboBox {
                model: ['hello', 'world', 'and', 'bye']
            }
        }

        FormControl {
            label.text: 'Text'
            control: TextField {
            }
        }

        FormControl {
            label.text: 'Something Long'
            control: TextField {

            }
        }
    }
}

You might omit the control when you declare it the default property Item control in FormControl.qml. Then however you might acidently add multiple controls, where the first will be lost.

I use the Row to benefit from the implicit height and width, but you could also use a Item and set the width and height to it's childrenRect.width/height. I am not sure, however, if this is robust.

like image 142
derM Avatar answered Feb 21 '26 15:02

derM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!