How exactly does addStretch work in QBoxLayout? How exactly does addStretch work in QBoxLayout? python python

How exactly does addStretch work in QBoxLayout?


The addStretch method adds a QSpacerItem to the end of a box layout. A QSpacerItem is an adjustable blank space.

  1. Using vbox.addStretch(1) will add a zero-width spacer-item thatexpands vertically from the top of the layout downwards.

    Using hbox.addStretch(1) will add a zero-height spacer-item thatexpands horizontally from the left of the layout rightwards.

  2. Without stretch, the layout will be determined by thesizePolicyof the widgets. For a QPushButton, this isQSizePolicy.Fixedfor the vertical dimension, andQSizePolicy.Minimumfor the horizontal dimension. If you wanted the buttons to expand inboth directions, you could do something like this:

        ok.setSizePolicy(QtGui.QSizePolicy.Minimum,                     QtGui.QSizePolicy.Minimum)    cancel.setSizePolicy(QtGui.QSizePolicy.Minimum,                         QtGui.QSizePolicy.Minimum)
  3. The argument passed to addStretch changes the stretch factor. If youadd a second stretch after the ok button:

        vbox = QtGui.QHBoxLayout()    vbox.addStretch(1)    vbox.addWidget(ok)    vbox.addStretch(2)    vbox.addWidget(cancel)

    you will see that the second spacer item grows twice as fast as thefirst. And if you set the first stretch to zero, it won't grow atall.

If you want more information, see the Layout Management article in the Qt docs. It's also a good idea to use Qt Designer to experiment with stuff like this, as it gives you immediate visual feedback and shows you all the default values of the various properties involved.