如何控制布局中 QFrame 的比例?

How to control the proportions of a QFrame in a layout?

这是我的代码。我的要求:如果 Window 增长,框架也会在两个方向上按比例扩展。我正在尝试使用 SetSize Policy,但什么也不会发生。如何实现?

import sys
from  PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class FrameExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Frame Example")
        self.setGeometry(100,100,600,600)

        self.frame = QFrame()
        self.frame.setFixedSize(200,200)
        # self.frame.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Fixed)
        self.frame.setStyleSheet("background-color:skyblue")

        self.frame1 = QFrame()
        self.frame1.setGeometry(QRect(10,10,600,600))
        self.frame1.resize(600,600)
        self.frame1.setStyleSheet("background-color:lightgreen")

        layout = QVBoxLayout()
        layout.addWidget(self.frame)
        layout.addWidget(self.frame1)
        self.setLayout(layout)

if __name__=="__main__":
    app = QApplication(sys.argv)
    countrywin =FrameExample()

    countrywin.show()
    sys.exit(app.exec_())

根据评论,您似乎希望顶部框架获得宽度的三分之一(即 200/600 == 1/3),高度保持固定 - 但它不应调整为小于任一方向的最小值.同时,底部框架应该只占用剩余的 space。

这可以通过首先设置 minimum-size and an appropriate size-policy on the top frame. Its proportions can then be controlled by putting it in a horizontal layout and adding stretchers 适当的拉伸因子(取决于框架的对齐方式)来实现。

这是一个基于您的代码的工作示例:

import sys
from  PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class FrameExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Frame Example")
        self.setGeometry(100, 100, 600, 600)

        self.frame = QFrame()
        self.frame.setStyleSheet("background-color:skyblue")

        self.frame.setMinimumSize(QSize(200, 200))
        self.frame.setSizePolicy(
            QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)

        hbox = QHBoxLayout()

        # align left
        hbox.addWidget(self.frame, 1)
        hbox.addStretch(2)

        # align centre
        # hbox.addStretch()
        # hbox.addWidget(self.frame)
        # hbox.addStretch()

        self.frame1 = QFrame()
        self.frame1.setStyleSheet("background-color:lightgreen")

        layout = QVBoxLayout()
        layout.addLayout(hbox)
        layout.addWidget(self.frame1)
        self.setLayout(layout)


if __name__=="__main__":
    app = QApplication(sys.argv)
    countrywin =FrameExample()

    countrywin.show()
    sys.exit(app.exec_())