title: How do I stop a custom widget from expanding in PyQt5?
body: <p>I'm trying to make a widget which contains many other widgets and I keep having problems with resizing the window: the widget keeps expanding even if I &quot;tell&quot; it not to. Here is my minimal example:</p>
  <pre class="lang-py prettyprint-override"><code>from PyQt5 import QtWidgets, QtGui, QtCore
  
  class CustomWidget(QtWidgets.QWidget):
      def __init__(self):
          super().__init__()
          self.layout  = QtWidgets.QGridLayout()
          self.button1 = QtWidgets.QPushButton(&quot;Button A&quot;)
          self.button2 = QtWidgets.QPushButton(&quot;Button B&quot;)
          self.label1  = QtWidgets.QLabel(&quot;Long label that can span multiple columns&quot;)
  
          self.layout.addWidget(self.button1, 0, 0)
          self.layout.addWidget(self.button2, 0, 1)
          self.layout.addWidget(self.label1, 1, 0, 1, 2)
          self.setLayout(self.layout)
  
  
  class App(QtWidgets.QWidget):
      def __init__(self):
          super().__init__()
          self.cw = CustomWidget()
          self.layout = QtWidgets.QVBoxLayout()
          self.layout.addWidget(self.cw)
  
          self.setLayout(self.layout)
          self.show()
  
  QtWidgets.QApplication.setStyle(QtWidgets.QStyleFactory.create(&quot;Fusion&quot;))
  app = QtWidgets.QApplication([])
  win = App()
  status = app.exec_()
  </code></pre>
  <p>This code does work however if I resize the window then all the buttons and labels get spread out over the screen which is not what I want.</p>
  <p>I've tried:</p>
  <ul>
  <li><p>Setting a fixed size: doesn't work because the label text can be different lengths and I want the widget to resize accordingly (but stay as small as possible)</p>
  </li>
  <li><p><code>self.setFixedSize(self.size())</code> doesn't do anything and sometimes makes it worse</p>
  </li>
  <li><p><code>self.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)</code> or any other size policy seems to do nothing</p>
  </li>
  </ul>
  <p>TL;DR I want my widget to shrink even if there's empty space but I don't want to set a fixed size.</p>
  <p>EDIT:</p>
  <p>I have <em>partially</em> solved the problem by passing in <code>alignment=QtCore.Qt.AlignLeft</code> to all the <code>self.layout.addWidget</code> calls. It doesn't totally get rid of the problem however it may be a step in the right direction.</p>