PDA

View Full Version : QListWidget width



colin207
20th June 2010, 23:46
Hi

What, precisely, controls the default width of a QListWidget. I want a list widget that makes itself exactly wide enough to display the width of its widest item but no more.

E.g. I would have expected the following simple code to produce a dialog with a list box exactly wide enough to hold the items "fred" and "bloggs" but no more. Yet the dialog that gets shown has a list widget some 5 times wider than necessary. Why?


QDialog dlg(this);
QListWidget* pListWidget = new QListWidget();
new QListWidgetItem("Fred", pListWidget);
new QListWidgetItem("Bloggs", pListWidget);
QVBoxLayout* pLayout = new QVBoxLayout();
pLayout->addWidget(pListWidget);
dlg.setLayout(pLayout);
dlg.exec();



What is the simplest, clean and reliable way to control the list width width without relying on pixel width constants. Code needs to be properly portable. Thanks

aamer4yu
21st June 2010, 05:23
Try setting different size policies and see if it works for you...
(QSizePolicy::Minimum)

colin207
21st June 2010, 06:34
Thanks. But I had already tried setting horz size policy on the QListWidget to Minimum. Makes no difference. Specifically I used:



QSizePolicy sp = pListWidget->sizePolicy();
sp.setHorizontalPolicy(QSizePolicy::Minimum);
pListWidget->setSizePolicy(sp);


Any other ideas?

SneakyPeterson
21st June 2010, 09:54
Have you tried setMinimumWidth() and setMaximumWidth? I just made this up on the fly, so it might not compile, but it should look something like this.


QDialog dlg(this);
QListWidget* pListWidget = new QListWidget();
QListWidgetItem fred = new QListWidgetItem("Fred", pListWidget);
QListWidgetItem bloggs = new QListWidgetItem("Bloggs", pListWidget);
QVBoxLayout* pLayout = new QVBoxLayout();
pLayout->addWidget(pListWidget);
dlg.setLayout(pLayout);
dlg->setMinimumWidth(fred->sizeHint().width()+bloggs->sizeHint().width());
dlg->setMaximumWidth(fred->sizeHint().width()+bloggs->sizeHint().width());
dlg.exec();

colin207
21st June 2010, 10:12
Thanks for the suggestion. But calling sizeHint().width() on the list widget items returns -1 which doesnt seem to help!

SneakyPeterson
21st June 2010, 10:45
Hehe, moment of stupidity. Fred and Bloggs are being handled by your pListWidget, so that's the size you care about.
These things always happen to me on Monday mornings...



QDialog dlg(this);
QListWidget* pListWidget = new QListWidget();
new QListWidgetItem("Fred", pListWidget);
new QListWidgetItem("Bloggs", pListWidget);
QVBoxLayout* pLayout = new QVBoxLayout();
pLayout->addWidget(pListWidget);
dlg.setLayout(pLayout);
dlg->setMinimumWidth(pListWidget->size());
dlg->setMaximumWidth(pListWidget->size());
dlg.exec();