I was creating an application with a QFrame on the left side and a control panel on the right. However, I cannot get the QFrame on the left to be sized properly. I created the following example to demonstrate the problem:
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()
I would expect a big red shape on the left but instead I get this:
Resizing the window (either at runtime by dragging or by setting the geometry in code) does resize the QFrame to neatly fill up half the screen. But I want it to have a predefined fixed size.
Why is frame.resize
not working as expected?
Found it. Using frame.setFixedSize()
does exactly what I want:
class MyFrame(QFrame):
def __init__(self, *args, **kwargs):
self.setFixedSize(300, 300) # < Added this line
The frame keeps it size and if I resize the whole window this is respected:
I am still not sure why resize()
does nothing.