How to change the default size of PySide window

GOAL

To change the default size that is initial size of the window in PySide2.

Environment

Windows 10
Python 3.8.7
PySide2 5.15.2

Method

I create a simple window as below.

import sys
from PySide2.QtWidgets import *

class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self._generateUI()

    def _generateUI(self):
        main_widget = QWidget()
        main_layout = QVBoxLayout()
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)
        button = QPushButton("Button")
        main_layout.addWidget(button)

def launch():
    app = QApplication.instance()
    if not app:
        app = QApplication(sys.argv)
    widget = MyMainWindow()
    widget.show()
    app.exec_()

launch()

How to change the variable size

Use resize() function at first to change the default size.

from PySide2 import QtCore

class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self._generateUI()
        self.resize(200, 300)

How to change the variable width and height

You can change only width or height of the window using height() or width() to get current size.

def launch():
    app = QApplication.instance()
    if not app:
        app = QApplication(sys.argv)
    widget = MyMainWindow()
    widget.show()
    widget.resize(250, widget.height())

Because the window size is adjusted to the contents of the window, resize after showing the window.

class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self._generateUI()
        print(self.width(), self.height())
        # output => 640 480

def launch():
    app = QApplication.instance()
    if not app:
        app = QApplication(sys.argv)
    widget = MyMainWindow()
    widget.show()
    print(widget.width(), widget.height())
    # output => 200 100

Appendix

How to change the fixed size

Use setFixedSize() to fix the size of window. (You can’t resize the window after using this function.)

class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setFixedSize(200, 300)
        self._generateUI()

How to change the fixed height and width.

Use setFixedWidth() and setFixedHeight(). If you use setFixedWidth(), you can still change the height of the window.

class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setFixedWidth(250)
        self._generateUI()