其他分享
首页 > 其他分享> > QML之TextEdit组件

QML之TextEdit组件

作者:互联网

TextEdit

TextEdit组件与TextInput类似,不过它支持用户输入多行文本,甚至可以通过textFormat属性支持富文本或者Markdown格式的文本内容。

TextEdit {
    id: _textEdit1
    x: 10
    y: 10
    width: 200
    height: 30
    focus: true
    textFormat: TextEdit.RichText
    text: "<b>Hello</b> <i>World!</i>"
}
 
TextEdit {
    id: _textEdit2
    x: 10
    y: 50
    width: 200
    height: 100
    textFormat: TextEdit.MarkdownText
    text: "
# The largest heading
## The second largest heading
###### The smallest heading
"
}

 

虽然TextEdit可以支持多行文本的输入,但是默认情况下,它并不支持对内容的滚动操作,也不支持鼠标拖拽。不过我们可以通过Flickable组件来实现这些效果。

Rectangle {
    id: _scrollbar
    anchors.right: _flickable.right
    y: _flickable.visibleArea.yPosition * _flickable.height
    width: 3
    height: _flickable.visibleArea.heightRatio * _flickable.height
    color: "gray"
    radius: 2
}

Flickable {
    id: _flickable
    x: 10
    y: 10
    width: 300
    height: 80
    contentWidth: _textEdit.paintedWidth
    contentHeight: _textEdit.paintedHeight
    clip: true

    TextEdit {
        id: _textEdit
        width: _flickable.width
        height: parent.height
        focus: true
        wrapMode: TextEdit.Wrap
        onCursorRectangleChanged: _flickable.ensureVisible(cursorRectangle)
        text: "
I never saw a Moor--
I never saw the Sea--
Yet know I how the Heather looks
And what a Billow be.

I never spoke with God
Nor visited in Heaven--
Yet certain am I of the spot
As if the Checks were given--
"
    }

    function ensureVisible(r) {
        if (contentX >= r.x)
            contentX = r.x
        else if (contentX + width <= r.x + r.width)
            contentX = r.x + r.width - width
        if (contentY >= r.y)
            contentY = r.y
        else if (contentY + height <= r.y + r.height)
            contentY = r.y + r.height - height
    }
}

 

小贴士:这里我们加上了一个简易的滚动条效果。通常情况下,这并不是最优的解决方案。因为Qt Quick Controls模块已经提供了一个ScrollBar组件,以及其他的单行和多行输入组件,我们后面会对其进行介绍。

获取更多信息,请关注作者公众号:程序员练兵场
在这里插入图片描述 

 

标签:10,width,height,flickable,TextEdit,QML,组件,id
来源: https://blog.csdn.net/Y03977211367Y/article/details/122385264