PDA

View Full Version : QListWidget: Resize to it's content



Fred
7th July 2014, 13:32
Hi,

I'm trying to resize a QListWidget to it's content with QFontMetrics, calculating the height and the width. The calculating of the width works perfectly, but it fails to calculate the right height.



QListWidget *widget = new QListWidget(this);
QFont font("Droid Sans", 12, false);
QFontMetrics fm(font);

int width = fm.width() * longestEntry + 10;
int height = fm.height() * widget.count() + 10;

widget->resize(width, height);

The problem is, that the space between the QListWidgetItems depends on the used font and QFontMetrics delivers only the height without the space.

http://img1.myimg.de/picture96a40_thumb.jpg (http://www.myimg.de/?img=picture96a40.jpg)
Is it possible to get these extra pixels so I can calculate the right height with

int height = (fm.height() + pixels) * widget.count();

Or is there another (better) way to resize the QListWidget to it's content?

Many thanks!

anda_skoa
7th July 2014, 14:41
See QFontMetrics::leading() and QFontMetrics::lineSpacing().

Cheers,
_

Fred
7th July 2014, 16:06
Thank you for your answer! But it does not working as expected, with qDebug() I get the following

qDebug() << fm.lineSpacing() << fm.leading() << fm.height()

16 -1 17

I don't know why but lineSpacing() (16 pixel) gives a smaller value as the height (17 pixel). But to calculate the height of the QListWidget correctly, the value must be greater than 17 pixel for each entry.
Any suggestions?

Many thanks!

anda_skoa
7th July 2014, 19:38
Hmm, strange.
Have you tried if that is true for other fonts as well?

Cheers,
_

Fred
8th July 2014, 12:01
I have tested it with different fonts and only a few gave positive values, all the rest gives -1. :(
I'm using Qt 4.8.5 on Linux.