【发布时间】:2021-09-06 15:55:12
【问题描述】:
我正在尝试将字符串截断指定长度而不截断任何单词。我尝试使用正则表达式来执行此操作,但是当我尝试使用变量来指定我希望字符串的长度时,它似乎不起作用。这是我的 QML 代码:
import QtQuick 2.0
Rectangle {
id: background
property string contactName: "John Doe"
property string lastText: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Hac habitasse platea dictumst quisque sagittis purus sit. Enim nunc faucibus a pellentesque."
property int lastTextMaxLen: 40
Image {
id: contactPhoto
width: 100
anchors.left: parent.left
anchors.top: parent.top
anchors.bottom: parent.bottom
source: "qrc:/qtquickplugin/images/template_image.png"
anchors.bottomMargin: 25
anchors.topMargin: 25
anchors.leftMargin: 25
fillMode: Image.PreserveAspectFit
}
Rectangle {
id: rectangle
y: 25
height: 100
color: "#ffffff"
anchors.verticalCenter: parent.verticalCenter
anchors.left: contactPhoto.right
anchors.right: parent.right
anchors.rightMargin: 20
anchors.leftMargin: 15
anchors.verticalCenterOffset: 0
Text {
id: contactNameTxt
width: 90
height: 25
text: contactName
anchors.left: parent.left
anchors.top: parent.top
font.pixelSize: 20
anchors.leftMargin: 0
anchors.topMargin: 25
font.bold: true
}
Text {
id: lastTextPreview
text: lastText.replace(new RegExp("/^(.{"+lastTextMaxLen+"}[^\s]*).*/"), "$1")
anchors.top: contactName.bottom
anchors.bottom: parent.bottom
font.pixelSize: 15
wrapMode: Text.NoWrap
anchors.bottomMargin: 20
anchors.topMargin: 10
}
}
}
当我使用上面的代码时,无论我为 lastTextMaxLen 设置的数字是多少,我的文本都会完整显示。然而,如果我替换该行:
text: lastText.replace(new RegExp("/^(.{"+lastTextMaxLen+"}[^\s]*).*/"), "$1")
与:
text: lastText.replace(/^(.{40}[^\s]*).*/, "$1")
它工作得很好。但是,我希望能够在变量中定义截断长度,以便可以根据小部件大小动态更改它。那么有人可以解决我的问题吗?
【问题讨论】:
标签: javascript qt qml