Search code examples
pythonpython-3.xpyqtpyqt5qwidget

PyQt5 QWidget set fixed width to smallest available size


I have a layout that I add a bunch of widget's (QPushButton's right now, but can be any QWidget element), by default they fill up the entire width when added. Since my custom size handling works of this width's to move elements they register each element as being the same size as the layout which causes my function to move them, even though they are smaller after I do a resize.

So, when I add a widget is there a way to shrink it to its minimum size to hold the content? Something along the lines:

item = QPushButton("somestuff") # | QLabel | QWidget | etc
item.setFixedWidth(item.contents.size().width())

Solution

  • To calculate the minimum width you can use QFontMetrics.

    item = QPushButton("somestuff") # | QLabel | QWidget | etc
    fm = QFontMetrics(item.font())
    item.setFixedWidth(fm.width(item.text()))