2

I have a subclass of QListWidget, the widget holds text items in a single column and multiple rows (the usual kind). I want the widget to resize itself to the minimum size where the text items will still be visible. I've tried using the resize() method with the contentsSize() argument, this will resize the widget's height to fit the text contents, however the width stays the same.

Here's a snippet of an overriden method that I'm testing this with:

override void mousePressEvent(QMouseEvent event)
{
    this.resize(this.contentsSize());
}

Note: This is in the D language, and I'm using the QtD wrapper library. Unless I'm doing something wrong it might even be a QtD bug (but I doubt it).

Andrej Mitrović
  • 3,322
  • 3
  • 20
  • 33

1 Answers1

1

If you're content to switch to a QTableView or QTreeView, you can call resizeColumnsToContents(), and resize your widget based on the resulting width. Otherwise you'll have to iterate over your QListWidget contents and get the maximum of the widths of the items.

Scott
  • 1,179
  • 7
  • 17
  • There doesn't seem to be a way to get the width of a QListWidgetItem. The sizeHint() property returns -1. Unless I resort to hand-calculating the font pixel size * chars * etc etc.., which is not flexible at all. – Andrej Mitrović Jan 19 '11 at 01:37
  • 1
    It's a challenge, and I don't have the correct answer on the tip of my tongue--in other words, there may be a more correct solution. But a good way to do it is to use QTextLayout::boundingRect(). In other words, iterate your items, and assuming the default font (if not, there are still ways), set up a QTextLayout with the text of each item, and call boundingRect().width() on that. – Scott Jan 25 '11 at 17:19