QWidget reports incorrect size

49 Views Asked by At

I have a program, where i am trying to center a window on screen. The window appears to be the size of my layout, which is somewhere around 200px wide, but QWidget.size() reports a width of 640px.

In the image is the actual window

My code is basically setting a QVBoxLayout to a QWindow, and then setting it visible with show(). Is the layout supposed to automatically report size to widget? Is there a way to get the size of the layout?

I've tried activating the layout, getting widget size as rect(), with no results

Heres the minimal example:

python
from PySide2.QtWidgets import *
import sys

class windowClass(QWidget):
    def __init__(self, layout):
        super(windowClass, self).__init__()
        self.setLayout(layout)

class layoutContainer:
    def getLayout():
        layout = QVBoxLayout()
        layout.addWidget(QLabel("This is a minimal example"))
        return layout

app = QApplication([])
        
layout = layoutContainer.getLayout()

window = windowClass(layout)

print(window.size()) # output: PySide2.QtCore.QSize(640, 480) 
window.show()



sys.exit(app.exec_())
1

There are 1 best solutions below

2
Brosbud On

FOR FUTURE REFERENCE

I've pinpointed the problem, and above code reflects it. The show() method sets window size FROM default to reflect layout. And thus, size() should only be called after the window is visible

Additionally should be noted, as @musicamante very clearly explained, if the widget positioning needs to be in any way accurate, sizeHint() should be utilized