简体   繁体   English

为什么QFontMetrics :: maxWidth返回这么大的值?

[英]Why does QFontMetrics::maxWidth return such a large value?

Windows 7 SP1 Windows 7 SP1
MSVS 2010 MSVS 2010
Qt 4.8.4 Qt 4.8.4

I want to determine the maximum size of a QLineEdit widget knowing the maximum number of characters that must fit into it. 我想确定QLineEdit小部件的最大大小,知道它必须容纳的最大字符数。

Therefore, I want to use: 因此,我想使用:

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

But this: 但是这个:

#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;
}

outputs this: 输出此:

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

Question: Why is the maximum width so much larger than the width of 'X'? 问题:为什么最大宽度比“ X”的宽度大得多? Is there some super large character in the font that I am unaware of? 我不知道字体中是否有一些超大字符?

This isn't a Qt issue, as the underlying Windows APIs ( GetTextMetrics and GetTextExtentPoint ) give the same values. 这不是Qt问题,因为基础Windows API( GetTextMetricsGetTextExtentPoint )提供相同的值。

Don't forget that a font may include many glyphs for unusual characters: ligatures, various long dashes, symbols, dingbats, and characters from alphabets you weren't expecting. 不要忘记,字体可能包含许多不寻常字符的字形:连字,各种长破折号,符号,装饰符号和您不期望的字母字符。

I'm mildly surprised this happens for the "monospace" font, but apparently, those are only fixed pitch for the subset of characters the font was designed for. 我对“等宽字体”会发生这种情况感到有些惊讶,但显然,这些只是字体设计所针对的字符子集的固定间距。 Courier New, for example has a few dozen characters that are more than twice the width of the average character, such as U+0713 SYRIAC LETTER GAMAL: ܓ. 例如,Courier New具有几十个字符,其宽度是平均字符宽度的两倍以上,例如U + 0713 SYRIAC LETTER GAMAL:ܓ。

If being right most of the time is sufficient, I'd take the average character width, round it up a bit, and multiply it out. 如果大部分时间正确,我将取平均字符宽度,将其四舍五入,然后相乘。 If the user needs to enter several unusually wide characters, you might need to scroll a little, but that's not the end of the world. 如果用户需要输入几个不寻常的宽字符,则可能需要稍微滚动一下,但这还不是世界末日。

If you know it's always going to be English, you may as well measure a capital W and use that. 如果您知道总是要用英语,则最好测量大写字母W并使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM