Taran
Taran

Reputation: 14126

PyQt QHBoxLayout inside QPushButton text is being truncated

I'm trying to place a checkbox and some text inside a button, but I'm having trouble getting the button to expand wide enough to see the full text.

enter image description here

self.check = QtGui.QCheckBox("long text", self)
self.checkLayout = QtGui.QHBoxLayout()
self.checkLayout.addWidget(self.check)
self.checkButton = QtGui.QPushButton(None, self)
self.checkButton.setLayout(self.checkLayout)

I've tried various combinations of adding stretches, setting the size policy, setting margins and styles etc. but haven't had any luck so far.

Thanks

Upvotes: 2

Views: 857

Answers (1)

Alexander Lutsenko
Alexander Lutsenko

Reputation: 2160

Add a layout to the button. Place the checkbox inside the layout. Looks like this is the only way for QWidget to automatically track a size of its subwidgets. But QWidget doesn't automatically resize itself to fit its content. You must invoke adjustSize function to do it.

class TestWidget(QtGui.QWidget):
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)

        self.check = QtGui.QCheckBox("very very long text")

        self.checkLayout = QtGui.QHBoxLayout()
        self.checkLayout.addWidget(self.check)

        self.checkButton = QtGui.QPushButton()
        self.checkButton.setLayout(self.checkLayout)
        self.checkButton.adjustSize()

        self.checkButton.setParent(self)

UPD: There is a problem with adjustSize. This function doesn't work for me if I call it after adding checkButton to the screen:

# works
self.checkButton.adjustSize()
self.checkButton.setParent(self)
# doesn't work
self.checkButton.setParent(self)
self.checkButton.adjustSize()

My solution is manual resizing instead of calling adjustSize:

self.checkButton.setFixedSize(self.checkLayout.sizeHint())

Upvotes: 3

Related Questions