使 QScrollArea 使用 QMainWindow 高度轴的所有可用 space

Make QScrollArea use all available space of QMainWindow height axis

我的 QMainWindow 受最大高度 900px 的限制。我希望 QScrollArea 在这个 window 的高度轴上使用所有可用的 space 如果该区域有能力增加高度。

当我 运行 应用程序 QMainWindow 选择了一些不是最大值的高度值时,但是如果我手动将 QMainWindow 拉伸到最大高度 QScrollArea 并且其中有很多小部件,它看起来也很漂亮。那么为什么它不从程序一开始就使用所有可用的 space?

这里是演示这种情况的代码片段:

class UI(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setFixedWidth(500)
        self.setMaximumHeight(900)

        mainWidget = QWidget()
        mainlLayout = QVBoxLayout()
        scrollArea = QScrollArea()

        mainWidget.setLayout(mainlLayout)

        scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scrollArea.setWidgetResizable(True)
        scrollArea.setWidget(mainWidget)
        self.setCentralWidget(scrollArea)

        for i in range(30):
            buts = QHBoxLayout()
            for j in range(3):
                buts.addWidget(QPushButton('Yet Another Button'))
            mainlLayout.addLayout(buts)


def main():
    app = QApplication(sys.argv)
    ui = UI()
    ui.show()
    sys.exit(app.exec_())

这里是程序启动后的window:

这里是拉伸后的 window 但看起来也不错:

下面的代码修复了 QScrollArea 高度的问题:

class UI(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setFixedWidth(500)
        self.setMaximumHeight(900)

        mainWidget = QWidget()
        mainlLayout = QVBoxLayout()
        self.scrollArea = QScrollArea()

        mainWidget.setLayout(mainlLayout)

        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setWidget(mainWidget)
        self.setCentralWidget(self.scrollArea)

        for i in range(30):
            buts = QHBoxLayout()
            for j in range(3):
                buts.addWidget(QPushButton('Yet Another Button'))
            mainlLayout.addLayout(buts)

        self.show()
        QApplication.processEvents()
        self.adjustScrollArea()

    def adjustScrollArea(self):
        step = 5
        while self.scrollArea.verticalScrollBar().isVisible() and self.height() < self.maximumHeight():
            self.resize(self.width(), self.height() + step)


def main():
    app = QApplication(sys.argv)
    ui = UI()
    sys.exit(app.exec_())

我用QApplication.processEvents()是因为self.show()执行后的语句self.scrollArea.verticalScrollBar().isVisible()只有在绘制gui,所有事件都处理完后才有效