您可能必须使用基于 0 的填充来实现所需的对齐方式——或者找到等宽字体,然后使用空格而不是 0
无论如何——这可能是一个解决方案:
import QtQuick 2.0
Item {
height: 480
width: 320
/* list of float strings to pad */
property var myFloats: ["6.9", "36.21", "4.632", "4225.2", "12.0"]
/* apply zero-based padding to the strings on startup
and output to the console */
Component.onCompleted: {
console.log(pad_floats());
}
/* function takes each decimal,and each integer separated by the .
and figures out the length of the longest one, then uses
a padding algorithm to add 0s to the start of the integers
and 0s to the back of decimals and returns an array */
function pad_floats() {
var longest_int = 0;
var longest_float = 0;
var newFloats = [];
for (var i = 0; i < myFloats.length; i++) {
var tmp_float = myFloats[i];
var tmp_int = tmp_float.split(".")[0]; // left side
var tmp_dec = tmp_float.split(".")[1]; // right side
/* check if either number is more digits than our longest one */
if (tmp_int.length > longest_int) {
longest_int = tmp_int.length;
}
if (tmp_dec.length > longest_float) {
longest_float = tmp_dec.length;
}
}
for (var u = 0; u < myFloats.length; u++) {
var tmp_float = myFloats[u];
var tmp_int = tmp_float.split(".")[0]; // left side of .
var tmp_dec = tmp_float.split(".")[1]; // right side of .
/* pad the two numbers */
var new_int = pad(parseInt(tmp_int), longest_int, "0");
var new_dec = pad(parseInt(tmp_dec), 0 - longest_float, "0");
/* combine the new numbers back into one */
var new_float = new_int + "." + new_dec;
/* add to our array to return */
newFloats.push(new_float);
}
return newFloats;
}
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
/* Heres the ListView to show the actual list of floats */
ListView {
width: 320
height: 480
anchors.fill: parent
anchors.left: parent.left
model: pad_floats() // our returned array from before
delegate: listDelegate // pointer to the Component below
}
Component {
id: listDelegate
Text {
text: modelData
font.pointSize: 11
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
}
}
运行此操作的结果是一个包含以下条目的 ListView:
0006.9
0036.21
0004.632
4225.2
0012.0
就是这样......就像我在答案顶部所说的那样 - 为了创建只有数字而没有额外 0 的所需结果,您必须使用具有相同空间量的字体对于每个字符,包括(空格)字符。
这些通常称为 Monotype 或 Monospace 字体。
通常这些字体会将“Mono”一词与其名称相关联,以便更轻松地找到它们。
找到好的单型字体后,在 pad_floats() 函数中替换以下代码:
旧代码
var new_int = pad(parseInt(tmp_int), longest_int, "0");
var new_dec = pad(parseInt(tmp_dec), 0 - longest_float, "0");
新代码
var new_int = pad(parseInt(tmp_int), longest_int, " ");
var new_dec = pad(parseInt(tmp_dec), 0 - longest_float, " ");
注意我如何将最后一个“0”参数更改为“”?最后一个字符串是填充字符串,所以你可以在里面放任何东西,它会用那个字符串填充。
享受吧。