Question

Running this code creates a simple dialog with a label, lineedit and two buttons. All the widgets beautifully respond to the dialog horizontal resizing. But the buttons at the bottom of the dialog do not stick to the lower edge of dialog window when it is being resized vertically. What would be a possible solution to make sure the buttons are always positioned at the bottom edge of dialog?

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication(sys.argv)



class mainWindow(QtGui.QMainWindow):

    def __init__(self):
        super(mainWindow, self).__init__()

        mainQWidget = QtGui.QWidget()
        mainLayout=QtGui.QFormLayout()
        mainLayout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow)

        label = QtGui.QLabel('My Label')  
        lineEdit = QtGui.QLineEdit()
        mainLayout.addRow(label, lineEdit)

        ButtonBox = QtGui.QGroupBox()
        ButtonsLayout = QtGui.QHBoxLayout()

        Button_01 = QtGui.QPushButton("Close")
        Button_02 = QtGui.QPushButton("Execute")

        ButtonsLayout.addWidget(Button_01)
        ButtonsLayout.addWidget(Button_02)

        ButtonBox.setLayout(ButtonsLayout)
        mainLayout.addRow(ButtonBox)

        mainQWidget.setLayout(mainLayout)
        self.setCentralWidget(mainQWidget)


if __name__ == '__main__':
    window = mainWindow()
    window.show()
    window.raise_() 
    window.resize(480,320)
    app.exec_()
Was it helpful?

Solution

I would suggest using a QVBoxLayout as your main layout, with a stretch between the QFormLayout and the button's QHBoxLayout.

As an example based on your current dialog:

import sys
from PyQt4 import QtGui


class MainWindow(QtGui.QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()

        label = QtGui.QLabel('My Label')
        line_edit = QtGui.QLineEdit()

        form_layout = QtGui.QFormLayout()
        form_layout.addRow(label, line_edit)

        close_button = QtGui.QPushButton('Close')
        execute_button = QtGui.QPushButton('Execute')

        button_layout = QtGui.QHBoxLayout()
        button_layout.addWidget(close_button)
        button_layout.addWidget(execute_button)

        main_layout = QtGui.QVBoxLayout()
        main_layout.addLayout(form_layout)
        main_layout.addStretch()
        main_layout.addLayout(button_layout)

        central_widget = QtGui.QWidget()
        central_widget.setLayout(main_layout)
        self.setCentralWidget(central_widget)


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.resize(480, 320)
    window.show()
    sys.exit(app.exec_())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top