【问题标题】:How to restrict maximum lines of user input in TextEdit in QML如何在 QML 的 TextEdit 中限制用户输入的最大行数
【发布时间】:2020-06-28 15:28:43
【问题描述】:

我目前正在尝试在矩形内实现文本编辑。问题是用户仍然可以在矩形范围之外打字。我已将 wrapMode 设置为 TextEdit.Wrap,但问题是来自 textedit 的文本可能会从矩形底部溢出。我试图通过使剪辑为真来解决这个问题,但用户仍然可以输入字符但看不到它。我该怎么办?

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


                }
            }

这是带有矩形的文本图像:未设置剪辑和 wrapMode:TextEdit.Wrap。这张图和我想要的相反

【问题讨论】:

    标签: qt qml


    【解决方案1】:

    实际上没有办法限制最大行数。从理论上讲,由于这是开源的,您可以做任何事情,但这需要一些努力。我可以建议一个解决方法:

    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);
                }
            }
        }
    }
    

    这种方法只是切断了在盒子外面找到的所有东西。

    【讨论】:

    • 嗨!这是一个很好的开始@folibis 我只是想知道是否有办法限制光标退出框外?我喜欢用户不能在框外写字的方式,但我希望光标留在框内
    • 你对上面的评论有什么建议吗?
    • 很抱歉给您带来了麻烦:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多