1

Windows 7 SP1
MSVS 2010
Qt 4.8.4

我想确定 QLineEdit 小部件的最大大小,知道它必须容纳的最大字符数。

因此,我想使用:

int QFontMetrics::maxWidth () const
Returns the width of the widest character in the font.

但是这个:

#include <QApplication>
#include <QFont>
#include <QFontMetrics>
#include <iostream>

using std::cout; using std::endl;

int main(int argc, char *argv[])
{
    QApplication app(argc,argv);

    QFontMetrics metrics(QApplication::font()); 
    cout << "Default -     Max width: " << metrics.maxWidth() << " Width of X: " << metrics.width('X') << endl;
    const QFont f("Monospace", 8);
    QFontMetrics metrics2(f); 
    cout << "Monospace 8 - Max width: " << metrics2.maxWidth() << " Width of X: " << metrics2.width('X') << endl;
    const QFont f2("Cambria", 16);
    QFontMetrics metrics3(f2); 
    cout << "Cambria 16 -  Max width: " << metrics3.maxWidth() << " Width of X: " << metrics3.width('X') << endl;
    return 0;
}

输出这个:

Default -     Max width: 23 Width of X: 6
Monospace 8 - Max width: 23 Width of X: 6
Cambria 16 -  Max width: 91 Width of X: 12

问题:为什么最大宽度比'X'的宽度大这么多?字体中是否有一些我不知道的超大字符?

4

1 回答 1

1

这不是 Qt 问题,因为底层 Windows API (GetTextMetricsGetTextExtentPoint) 提供相同的值。

不要忘记,一种字体可能包含许多不寻常字符的字形:连字、各种长破折号、符号、dingbats 以及您未曾预料到的字母表中的字符。

我对“等宽”字体会发生这种情况感到有点惊讶,但显然,这些只是字体设计用于的字符子集的固定间距。例如,Courier New 有几十个字符,其宽度是普通字符的两倍以上,例如 U+0713 SYRIAC LETTER GAMAL: 。

如果大部分时间都是正确的就足够了,我会取平均字符宽度,将其四舍五入,然后将其相乘。如果用户需要输入几个异常宽的字符,您可能需要稍微滚动一下,但这并不是世界末日。

如果您知道它总是会是英语,那么您不妨测量一个大写字母 W 并使用它。

于 2013-01-04T23:37:25.563 回答