QML text area, prevent resize of text area

Viewed 273

I am trying to create a simple window in QML with a huge text area in the center and a couple of buttons at the bottom,

bellow is the code

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12

Window {
    id: mainWindow
    width: 500
    height: 300
    visible: true
    title: qsTr("Hello World")
    flags: Qt.WindowCloseButtonHint | Qt.CustomizeWindowHint | Qt.Dialog | Qt.WindowTitleHint

    ColumnLayout{
        anchors.fill: parent
        anchors.margins: 5

        RowLayout {
            Layout.alignment: Qt.AlignTop

            TextArea {
                text: "Hello world!"       
            }
        }

        RowLayout {
            Layout.alignment: Qt.AlignBottom | Qt.AlignRight

            Button {
                text: "Ok"
            }
            Button {
                text: "Cancel"
            }
        }
    }
}

however when i press enter key multiple times enough to reach almost at the bottom of the text area, the button moves because the text area resizes, how do I prevent this? How do I set the text area so that it doesnt resize and push the buttons out of the window, but still be responsive that if the window resize it maintains its positions like buttons will still be buttom right and text area adjusts based on anchor.

1 Answers

It sounds like you want your TextArea to fill the space above the buttons, but your present code is not doing this. If I add a transparent red Rectangle to fill your TextArea, you can see what is happening:

TextArea only as large as text

The reason for this is that, by default, the TextArea is only as large as its text (implicitHeight/implicitWidth). Instead, if you want it to fill the top area, you need to specify Layout.fillHeight and Layout.fillWidth. This also means you maybe shouldn't have to rely on Layout.Alignment. Here is your code updated with these fills specified and some alignment properties removed:

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12

Window {
    id: mainWindow
    width: 500
    height: 300
    visible: true
    title: qsTr("Hello World")
    flags: Qt.WindowCloseButtonHint | Qt.CustomizeWindowHint | Qt.Dialog | Qt.WindowTitleHint

    ColumnLayout{
        anchors.fill: parent
        anchors.margins: 5

        RowLayout {

            TextArea {
                text: "Hello world!"
                Layout.fillHeight: true
                Layout.fillWidth: true
            }
        }

        RowLayout {
            Layout.alignment: Qt.AlignRight

            Button {
                text: "Ok"
            }

            Button {
                text: "Cancel"
            }
        }
    }
}

You can see the result if we add another transparent colored Rectangle to make it visually clear what is happening:

enter image description here

Related