我也遇到过这个问题,没有解决办法。但是,在 Qt 5.4 中,添加了 FontMetrics 和 TextMetrics QML 类型。
文本度量
FontMetrics 有一个全面的 API,它反映了 C++ QFontMetricsF 类,其中一些是命令式的(函数)。 TextMetrics 采用 FontMetrics 中的函数,并为方便起见将它们设为声明性(属性),加上一些额外的属性以确保完整性。
给定一些文本字符串,TextMetrics 将为您提供tightBoundingRect 属性,顾名思义,它是围绕字符串的紧密边界矩形,没有您通常看到的额外空间。从仅包含数字的字符串的高度中获取该高度,您会得到多余的高度,而不是可以用作负间距:
import QtQuick 2.4
Item {
Rectangle {
anchors.fill: parent
TextMetrics {
id: metrics
text: "1"
}
Column {
anchors.fill: parent
anchors.bottomMargin: 5
spacing: -(metrics.height - metrics.tightBoundingRect.height)
Text { text: "123" }
Text { text: "123" }
Text { text: "123" }
}
}
}
注意文档中的warning:
警告:在 Windows 上调用此方法非常慢。
如果您只在 TextMetrics 对象上设置一次文本/字体,那应该不是问题,因为它只会计算一次。
行高
另一种但粗略的方法基本上是猜测每个 Text 项目的 lineHeight 属性的值。
import QtQuick 2.0
Item {
Rectangle {
anchors.fill: parent
Column {
anchors.fill: parent
anchors.bottomMargin: 5
Text { text: "123"; lineHeight: 0.8 }
Text { text: "123"; lineHeight: 0.8 }
Text { text: "123"; lineHeight: 0.8 }
}
}
}
负间距
正如 Shubhanga 所说,负间距也可以,但也不是很好:
import QtQuick 2.0
Item {
Rectangle {
anchors.fill: parent
Column {
anchors.fill: parent
anchors.bottomMargin: 5
spacing: -4
Text { text: "123" }
Text { text: "123" }
Text { text: "123" }
}
}
}
文字高度
同样,Shubhanga 提到,明确设置文本的高度是可行的,但仍然涉及猜测。与上述两种解决方案一样,每次更改字体大小时,您都必须更改从高度中减去的值,并且它不会在设备之间缩放(低 DPI 台式电脑与高 DPI 移动设备):
import QtQuick 2.0
Item {
readonly property int heightAdjustment: 5
Rectangle {
anchors.fill: parent
Column {
anchors.fill: parent
anchors.bottomMargin: 5
Text {
text: "123";
height: implicitHeight - heightAdjustment
}
Text {
text: "123";
height: implicitHeight - heightAdjustment
}
Text {
text: "123";
height: implicitHeight - heightAdjustment
}
}
}
}