如何将小部件粘贴到对话框边缘

How to stick widgets to dialog edges

如何在调整对话框大小时使 lineedit 粘在对话框的顶部,button 粘在对话框的下边缘?

from PyQt5.QtWidgets import *

class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setLayout(QVBoxLayout())

        layout = QHBoxLayout()
        self.layout().insertLayout(0, layout)
        lineedit = QLineEdit(self)
        layout.addWidget(lineedit)

        button = QPushButton(self)
        button.setText('ok')
        self.layout().addWidget(button)
        self.show()

app = QApplication(list())
dialog = Dialog()
app.exec_()

向布局添加垂直 spacer:

from PyQt5.QtWidgets import *

class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setLayout(QVBoxLayout())

        layout = QHBoxLayout()
        self.layout().insertLayout(0, layout)
        lineedit = QLineEdit(self)
        layout.addWidget(lineedit)

        # version (1): add vertical, expanding spacer item
        self.layout().addItem(
            QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding))

        # version (2): use "addStretch"
        # self.layout().addStretch()

        button = QPushButton(self)
        button.setText('ok')
        self.layout().addWidget(button)
        self.show()

app = QApplication(list())
dialog = Dialog()
app.exec_()

A QSpacerItem 只是一个无样式的空白 space,根据其大小策略占用布局中的水平和垂直 space。

QSpacerItem的参数:

  • w - 首选宽度,0
  • h - 首选身高,0
  • hPolicy - 水平尺寸策略,QSizePolicy.Minimum => 首选宽度足够,项目不会水平扩展
  • vPolicy - 垂直尺寸政策,QSizePolicy.Expanding => 该项目可以使用额外的 space,因此将垂直扩展并占用所有可用空间 space

详情见https://doc.qt.io/qt-5/qspaceritem.html#QSpacerItem and http://doc.qt.io/qt-5/qsizepolicy.html#Policy-enum