Linked Questions

Popular Questions

PyQt5: How to Get Dimensions of Displayed Widgets

Asked by At

I have PyQt5 QLabels that expand/contract as the QMainWindow size changes. I want to get the dimensions of the QLabels when the QMainWindow is sized to anything other that its initial dimensions.

The script below creates two QLabels in a QMainWindow. The QLabels expand but the top QLabel has a fixed height. The QMainWindow is created with dimensions 400x300 and and displays as screen maximized using showMaximized() (in my case, 1920 x 1080). The script prints the dimensions of the QLabels before and after the QMainWindow displays. Prior to display, width() and height() return default QLabel values and after display (screen maximized) width() and height() return values as if the QMainWindow has physical dimensions of 400x300. Here is wat is printed:

label_1 Size Before Expanding:  100 100
label_2 Size Before Expanding:  100 30
label_1 Size After Expanding:  378 100
label_2 Size After Expanding:  378 171

How can I get the true dimensions for the QLabels when the QMainWindow is maximized? I'm running in a Windows environment.

from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy, QLabel, QVBoxLayout, QWidget
import sys

class MainWindow(QMainWindow):  
    def __init__(self, parent=None):
        super().__init__(parent)
        
        central_widget = QWidget()
        self.setCentralWidget(central_widget)        
        self.setGeometry(100, 100, 400, 300)
        self.layout = QVBoxLayout(central_widget)
        
        self.label_1 = QLabel(self)
        self.label_1.setStyleSheet('background-color: green')
        self.label_1.setFixedHeight(100)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.label_1.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.label_1)
        
        self.label_2 = QLabel(self)
        self.label_2.setStyleSheet('background-color: red')
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.label_2.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.label_2)
        
        print('label_1 Size Before Expanding: ', self.label_1.width(), self.label_1.height())
        print('label_2 Size Before Expanding: ', self.label_2.width(), self.label_2.height())
        self.showMaximized()
        print('label_1 Size After Expanding: ', self.label_1.width(), self.label_1.height())
        print('label_2 Size After Expanding: ', self.label_2.width(), self.label_2.height())
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    app.exec()

Related Questions