Python – PyQt5 QWidget sets the fixed width to the smallest available size

PyQt5 QWidget sets the fixed width to the smallest available size… here is a solution to the problem.

PyQt5 QWidget sets the fixed width to the smallest available size

I

have a layout where I add a bunch of widgets (now QPushButton, but it can be any QWidget element) that by default fill the entire width when added. Since my custom sizing handles use this width to move elements, they register each element as the same size as the layout, which causes my function to move them even though they get smaller after I resize.

So, when I add a widget, is there a way to shrink it to the minimum size to accommodate the content? Stuff along the line:

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()))

Related Problems and Solutions