3

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_()
4

1 回答 1

2

我建议使用 QVBoxLayout 作为您的主要布局,并在 QFormLayout 和按钮的 QHBoxLayout 之间进行拉伸。

作为基于您当前对话框的示例:

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_())
于 2014-03-06T21:01:07.570 回答