TextArea是qml的一个富文本显示控件,可以显示文字,表情,图片等,在使用的过程中有时我们需要控制文本的宽度,超出部分用...表示,那么譔如何实现呢,虽然TextArea没有Text中的elide属性,但是可以借助TextMetrics实现这种效果,下面看具体的示例:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
TextMetrics{
id: textMetrics
elide: Text.ElideRight
elideWidth: 600
text: "Negative insets can be used to make the background larger than the popup. The following example uses negative insets to place a shadow outside the popup's boundaries:"
}
//文字显示缩略
TextArea {
id: referMessage
color: "#000000"
anchors.top: parent.top
anchors.topMargin: 100
anchors.left: parent.left
anchors.leftMargin: 100
width: 300
height: 40
text: textMetrics.elidedText //文字缩略
font.pixelSize: 14
font.weight: Font.Light
wrapMode: TextArea.WrapAnywhere
readOnly: true
verticalAlignment: Text.AlignVCenter
focusReason: Qt.MouseFocusReason
textFormat: TextArea.AutoText
background: Rectangle {
anchors.fill: parent
color: "#ffff00"
}
}
Component.onCompleted:
{
console.log("str=====", str, str.length)
}
}
运行结果: