Shrink a QPushButton width to the minimum

noisygecko picture noisygecko · Jan 19, 2013 · Viewed 15.9k times · Source

This seems like such a simple thing, but I can't seem to figure it out. How do I make the button the minimum width. It keeps expanding to the width of the layout I put it in. In the following example, the QPushButton width ends up the same as the QLabel:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class MyWindow(QWidget):

    def __init__(self,parent = None):

        QWidget.__init__(self,parent)

        layout = QVBoxLayout()
        layout.addWidget(QLabel('this is a really, really long label that goes on and on'))
        layout.addWidget(QPushButton('short button'))

        self.setLayout(layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

Answer

user178047 picture user178047 · Mar 11, 2014

setMaximumWidth works for me

from PyQt4 import QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        layout = QtGui.QHBoxLayout()
        texts = [":)",
                 "&Short",
                 "&Longer",
                 "&Different && text",
                 "More && text",
                 "Even longer button text", ]
        for text in texts:
            btn = QtGui.QPushButton(text)
            double = text.count('&&')
            text = text.replace('&', '') + ('&' * double)
            width = btn.fontMetrics().boundingRect(text).width() + 7
            btn.setMaximumWidth(width)
            layout.addWidget(btn)
        self.setLayout(layout)

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)
    mainWin = Window()
    mainWin.show()
    sys.exit(app.exec_())