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

时间:2018-02-09 05:32:24

标签: python qt pyqt qdialog

当调整大小时,如何使lineedit坚持到顶部并button到对话框的下边缘?

enter image description here

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

1 个答案:

答案 0 :(得分:2)

在布局中添加垂直间隔:

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

QSpacerItem只是一个没有样式的空白空间,根据其大小政策在布局中消耗水平和垂直空间。

QSpacerItem的参数:

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

有关详细信息,请参阅https://doc.qt.io/qt-5/qspaceritem.html#QSpacerItemhttp://doc.qt.io/qt-5/qsizepolicy.html#Policy-enum