How to restrict maximum lines of user input in TextEdit in QML

Viewed 1453

I am currently trying to implement a textedit within a rectangle. The problem is that the user is still able to type beyond the confines of the rectangle. I have set the wrapMode to TextEdit.Wrap, but the problem is that the text from the textedit can spill over from the bottom of the rectangle. I tried to fix this by making clip true, but the user is still able to type characters but not see it. What do I do?

import QtQuick 2.12
import QtQml.Models 2.12
import QtQuick.Controls 2.12
import QtQuick.Controls.Styles 1.4
import QtQuick.Layouts 1.12
import QtGraphicalEffects 1.12
import QtMultimedia 5.0

  Rectangle{

                anchors{
                    top: parent.top
                    topMargin: parent.height/15
                    left: parent.left
                    leftMargin: parent.width/15
                    right: parent.right
                    rightMargin: parent.width/15
                    bottom: parent.bottom
                    bottomMargin: parent.height/1.2
                }
                color: 'white'
                z: 1
                radius: 15
                TextEdit{
                    clip: true
                    cursorPosition: 5
                    anchors.fill: parent
                    wrapMode: TextEdit.Wrap


                }
            }

This is an image of the text with rectangle: clip is not set and wrapMode: TextEdit.Wrap. This image is the opposite of what I want

1 Answers

There is actually no way to limit the maximum number of rows. Theoretically, since this is open source, you can do anything, but it will require some effort. I can suggest a workaround:

Rectangle {
    id: container
    width: 200
    height: 40
    anchors.centerIn: parent
    color: "orange"
    TextEdit {
        id: txt
        anchors.fill: parent
        padding: 3
        font.pixelSize: 14
        focus: true
        wrapMode: TextEdit.Wrap
        onTextChanged: {
            var pos = txt.positionAt(1, container.height + 1);
            if(txt.length >= pos)
            {
                txt.remove(pos, txt.length);
            }
        }
    }
}

This method just cuts off everything that is found outside of the box.

Related