[PyQt5 5.15] QListWidgetItem.setSizeHint not working
-
I just updated from PyQT5 5.14.2 to 5.15 and setting the height of list items using QListWidgetItem.setSizeHint appears to have stopped working. Here is a simple example that worked in 5.14.2 and does not work with 5.15:
import sys from PyQt5.QtWidgets import QApplication, QListWidget, QListWidgetItem, QMainWindow, QLabel from PyQt5.QtCore import QSize class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setWindowTitle("List Widget Sample") listWidget = QListWidget() self.setCentralWidget(listWidget) for x in range(5): item = QListWidgetItem('item {}'.format(x+1)) item.setSizeHint(QSize(-1, 100)) listWidget.addItem(item) app = QApplication(sys.argv) window = MainWindow() window.show() app.exec_()
Am I using the setSizeHint() method incorrectly or could this be a bug in the latest version? Is there a better way to set the height of list widget items?
-
Hi and welcome to devnet,
I find a negative value for a size hint surprising.
Can you add a picture what you had before and now ?
By the way, which OS are you on ? -
Hi, thanks for the reply.
I'm running on Windows 10.
Here is a before/after photo:
The default values for QListWidgetItem.sizeHint() is (-1, -1), so I assumed they are valid values. I just tried changing it to (0, 100), and it appears to work now. So I take it negative values are invalid, even though they are the default values? If I only want to apply the size hint to the height and keep the width stretched, is specifying 0 for the width considered the correct approach?
-
@flashk
https://doc.qt.io/qt-5/qsize.html#QSizebool QSize::isValid() const
Returns true if both the width and height is equal to or greater than 0; otherwise returns false.
So technically
QSize(-1, 100)
could be treated as invalid. Perhaps behaviour now reflects this at 5.15. -
The default -1, -1 is explained in the constructor documentation. By default you create an invalid QSize if giving no parameters.
-
The behavior is indeed new with 5.15.
The change makes it possible to reset the background, foreground, or size hint by passing a default constructed QBrush or QSize.
https://github.com/qt/qtbase/commit/96c27eb710a37780e79e09df2ebce1d5e4922c9d