Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QListWidget adjust size to content

Tags:

qt

pyqt

Is it possible to adjust QListWidget height and width to it's content?

sizeHint() always returns 256, 192 no matter what its content is.
QListWidgetItem's sizeHint() returns -1, -1, so I can not get content width.

Problem the same as here - http://www.qtcentre.org/threads/31787-QListWidget-width , but there is no solution.

enter image description here

import sys from PyQt4.QtGui import *  class MainWindow(QWidget):     def __init__(self, parent=None):         QWidget.__init__(self, parent)          list = QListWidget()         list.addItem('111111111111111')          vbox = QVBoxLayout(self)         vbox.addWidget(list)  app = QApplication(sys.argv) myapp = MainWindow() myapp.show() sys.exit(app.exec_()) 
like image 678
Qiao Avatar asked Jun 13 '11 23:06

Qiao


2 Answers

sizeHint() always returns 256, 192 no matter what its content is.

Thats because this is the size of the QListWidget, the viewport, not the items. sizeHintForColumn() will give you the max size over all items, so you can resize the widget like this:

list.setMinimumWidth(list.sizeHintForColumn(0)) 

If you don't want to force minimum width, then subclass and provide this as the size hint instead. E.g.:

class ListWidget(QListWidget):   def sizeHint(self):     s = QSize()     s.setHeight(super(ListWidget,self).sizeHint().height())     s.setWidth(self.sizeHintForColumn(0))     return s 
like image 117
gwohpq9 Avatar answered Sep 24 '22 22:09

gwohpq9


Using takois answer I played around with the sizeHintForColumn or sizeHintForRow and found that you have to add slightly larger numbers, because there might be some style dependent margins still. ekhumoros comment then put me on the right track.

In short the full size of the list widget is:

list.sizeHintForColumn(0) + 2 * list.frameWidth() list.sizeHintForRow(0) * list.count() + 2 * list.frameWidth()) 

According to the comment by Violet it may not work in Qt 5.

Also be aware that setting the size to the content, you don't need scrollbars, so I turn them off.

My full example for a QListWidget ajusted to its content size:

from PySide import QtGui, QtCore  app = QtGui.QApplication([])  window = QtGui.QWidget() layout = QtGui.QVBoxLayout(window) list = QtGui.QListWidget() list.addItems(['Winnie Puh', 'Monday', 'Tuesday', 'Minnesota', 'Dracula Calista Flockhart Meningitis', 'Once', '123345', 'Fin']) list.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) list.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) list.setFixedSize(list.sizeHintForColumn(0) + 2 * list.frameWidth(), list.sizeHintForRow(0) * list.count() + 2 * list.frameWidth()) layout.addWidget(list)  window.show()  app.exec_() 
like image 33
Trilarion Avatar answered Sep 25 '22 22:09

Trilarion