qmlalignmentqtquick2qtquickcontrols2baseline

QML baseline alignment without using a layout


I want to use baseline alignment anchor without using any fancy RowLayouts, etc. I want to use bottom anchor of a label be anchored with the baseline of the text edit. I thought, that baseline of controls without text is a top anchor, and for controls with text is somewhere between top and bottom anchors. But for my TextEdit it is the top anchor, which is unexpected

        Rectangle {
            width: 320
            height: 100
            border.width:  1

            Label {
                id: l
                text: "Description "
                height: 40
                anchors.bottom: te1.baseline
            }
            TextField {
                id: te1
                text: "Some test"
                height: 35
                anchors.left: l.right
                y: parent.height /  2
            }
        }

I tried demos with Qt5&6 and with default controls and QtQuick.Controls. By some reason the baseline of the textedit is the top. Why?

enter image description here

Update: The desired result I put on the screenshot below the actual one. I tried to calculate manually offsets for the label using the sizes of controls and font's metrics. Sadly, I still have magic constants there, which is not portable between various machines

FontMetrics {
    id: fontMetrics
    font.family: "Arial"
    font.pointSize: defaultFontSize
}

Rectangle {
    width: 320
    height: 120
    border.width:  1
    Text {
        id: l3
        text: "Description:"
        height: 15
        width: 150
        x: 0
        y: te3.y + te3.height / 2 - fontMetrics.height / 2 - 4
        font.family: "Arial";
        font.pointSize: defaultFontSize
    }
    TextField {
        id: te3
        text: "asdf2222"
        font.family: "Arial"
        font.pointSize: defaultFontSize
        background: Rectangle { color: "lightgray" }
        height: 50
        width: 100
        y: parent.height /  2
        anchors.left: l3.right
    }
}

Solution

  • Does below get the job done for you?

    Rectangle {
      width: 320
      height: 200
      border.width:  1
      color: "black"
      Label {
        id: l
        height: 40
        text: "Description: "
        anchors.baseline: te1.baseline
        // y: te1.y
      }
      TextField {
        id: te1
        height: 35
        text: "Some test"
        anchors.left: l.right
        y: parent.height /  2
      }
    }