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

1.2k views Asked by At

It's My Code. My Requirement: if the Window Grows the frame also expands as per ratio in both directions. I am trying with SetSize Policy, but nothing will happen. How to achieve it?

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

There are 1 answers

3
ekhumoro On BEST ANSWER

From the comments, it appears you want the top frame to get a third of the width (i.e. 200/600 == 1/3), with the height remaining fixed - but it should not resize smaller than the minimum in either direction. Meanwhile, the bottom frame should just take up whatever space is left over.

This can be achieved by firstly setting the 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 with appropriate stretch factors (depending on how the frame should be aligned).

Here is a working example based on your code:

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