PyQt5 - QFrame 大小在窗口中被忽略

问题描述

我正在创建一个应用程序,左侧有一个 qframe,右侧有一个控制面板。但是,我无法正确调整左侧的 qframe 大小。我创建了以下示例来演示该问题:

import sys
from PyQt5.QtWidgets import qframe,QApplication,QWidget,QVBoxLayout,QHBoxLayout,\
    QLabel


class MainWindow(QWidget):
    """Main Windows for this demo."""

    def __init__(self):
        """Constructor."""
        super().__init__()

        self.frame = MyFrame(self)

        layout_main = QHBoxLayout(self)
        layout_left = QVBoxLayout()
        layout_right = QVBoxLayout()

        layout_main.addLayout(layout_left)
        layout_main.addLayout(layout_right)

        self.frame.resize(600,600)
        layout_left.addWidget(self.frame)

        self.label = QLabel('I am on the right')
        layout_right.addWidget(self.label)

        # self.setGeometry(300,100,900,900)

        self.show()


class MyFrame(qframe):
    """Custom frame."""

    def __init__(self,*args,**kwargs):

        super().__init__(*args,**kwargs)

        self.setFrameStyle(qframe.Panel | qframe.Raised)
        self.setStyleSheet('qframe { background-color: red; }')


def main():
    """Main function."""

    app = QApplication([])
    window = MainWindow()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

我希望左边有一个大红色的形状,但我得到了这个:

enter image description here

调整窗口大小(在运行时通过拖动或通过在代码中设置几何图形)确实调整 qframe 的大小以整齐地填满屏幕的一半。但我希望它有一个预定义的固定大小。

为什么 frame.resize 没有按预期工作?

解决方法

找到了。使用 frame.setFixedSize() 正是我想要的:

class MyFrame(QFrame):

    def __init__(self,*args,**kwargs):

        self.setFixedSize(300,300)  # < Added this line

框架保持其大小,如果我调整整个窗口的大小,这将受到尊重:

enter image description here

我仍然不知道为什么 resize() 什么都不做。