Reputation: 375
Windows 7 SP1
MSVS 2010
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.
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'? Is there some super large character in the font that I am unaware of?
Upvotes: 1
Views: 930
Reputation: 47954
This isn't a Qt issue, as the underlying Windows APIs (GetTextMetrics
and GetTextExtentPoint
) give the same values.
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: ܓ.
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.
Upvotes: 1