How To Resize PyQt Programs

I recently ran into a problem with my m360Encrypt program where, when loaded onto my laptop which has a 4K screen that is only 13 inches wide, some of the bottom of the program was cut off underneath the task bar. The problem lies in how Windows tries to automatically resize it for high definition screens.

I searched the internet high and low for a solution, but there isn’t one out there. The best stackExchange has to offer is to enable the resize feature of your layout.

But what if you don’t have a layout? What if, instead of having all of your elements stacked horizontally or vertically, or in a graphy – you have them placed absolutely in the window?

Here’s how I solved the problem:

First: get the absolute values you intended to have when you created your window. You’re going to want to do this as soon as you instantiate your window – so somewhere in your init function of your window class

self.originalWindowWidth = self.width()
self.originalWindowHeight = self.height()

Next : take every single element you have that has a size and put it in a dictionary, with it’s original size as the value (alternatively, you could use a list, because you may not ever need the original size. I use the original size later, so I did it this way):

self.widgetDict = { self.label : QtCore.QRect(110, 20, 181, 31),
self.label_2 : QtCore.QRect(110, 50, 151, 16),
self.tabWidget : QtCore.QRect(30, 130, 791, 661),
self.comboBox : QtCore.QRect(80, 20, 611, 31),
self.comboBox_2 : QtCore.QRect(80, 60, 611, 31),
self.textEdit_6 : QtCore.QRect(80, 100, 611, 521),

}

Finally: whenever someone resizes the window, set x and y and also the height and width of each item to change to a percentage of the difference in size:

def resizeEvent(self, event):
windowwidth = self.width()
windowheight = self.height()
widthPercentChange = (windowwidth / self.originalWindowWidth)
heightPercentChange=(windowheigth / self.oringalWIndowHeight)

for key, value in self.widgetDict.items():
key.setGeometry(value.x() * widthPercentChange, value.y() * heightPercentChange, value.width() * widthPercentChange, value.height() * heightPercentChange)

And viola! Now whenever the window is resized, everything in the window will shrink or stretch in the same proportion.

Leave a Reply

Your email address will not be published.