I have essentially two buttons in a grid layout, with code written to save window size when refreshing the program. However, this presents one issue--despite having the window size saved, the window will always expand slightly, which becomes more and more noticeable as you reload the program again and again.
Here's my code if you want to see the effect:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from configparser import ConfigParser
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.loadDefaults()
self.resize(int(self.windowWidth),int(self.windowHeight))
self.setSizePolicy(QSizePolicy.Policy.Fixed,QSizePolicy.Policy.Fixed)
size=QSize(int(self.windowWidth),int(self.windowHeight))
container=QWidget()
layout=QGridLayout()
button=QPushButton("button1")
button2=QPushButton("button2")
layout.addWidget(button)
layout.addWidget(button2)
container.setLayout(layout)
self.setCentralWidget(container)
def resizeEvent(self, a0: QResizeEvent) -> None:
self.windowWidth=self.frameGeometry().width()
self.windowHeight=self.frameGeometry().height()
self.saveSettings()
return super().resizeEvent(a0)
def loadDefaults(self):
config=ConfigParser()
config.read('config.ini')
try:
config.add_section('settings')
config['settings']={
'windowWidth':int(self.screen().size().width()/2),
'windowHeight':int(self.screen().size().height()/2),
}
self.windowWidth=self.screen().size().width()/2
self.windowHeight=self.screen().size().height()/2
print("no ini file")
except:
self.windowWidth=config['settings'].getint('windowWidth')
self.windowHeight=config['settings'].getint('windowHeight')
print("ini file found")
with open('config.ini', 'w') as f:
config.write(f)
def saveSettings(self):
config=ConfigParser()
config.read('config.ini')
config['settings']={
'windowWidth':self.windowWidth,
'windowHeight':self.windowHeight,
}
with open('config.ini', 'w') as f:
config.write(f)
app=QApplication(sys.argv)
window=MainWindow()
window.show()
sys.exit(app.exec())
How can I prevent the window from resizing due to its child widgets, without forcing either of those aspects to have a fixed size?
I've looked into several posts: