pyjamas
pyjamas

Reputation: 5389

PyQt size() returns wrong size before showing the widget?

I am trying to match the size of button1 to button2 by checking the size of button1 and then setting the size of button2 to match, but size() on button1 returns the incorrect value of (640, 480) unless I show() it first. But if I show it before I am done setting up my layouts it flickers on the screen while subsequent code runs which I don't want.

How can I get around this?

Here is a minimal example:

import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import QSize
import random

class MyButton(QtWidgets.QPushButton):
    def __init__(self):
        super().__init__("BUTTON1")

    def sizeHint(self):
        return QSize(100,100)

if __name__=='__main__':

    app = QtWidgets.QApplication(sys.argv)

    # Button with sizeHint 100x100
    btn1 = MyButton()

    # There is a chance this button will be sized differently than its sizeHint wants
    if random.randint(0, 1):
        btn1.setFixedHeight(200)

    # This line works if btn1.setFixedHeight was called, but otherwise gives the wrong height of 480px
    height = btn1.size().height()

    # I want btn2 to be the same height as btn1
    btn2 = QtWidgets.QPushButton("BUTTON2")
    btn2.setFixedHeight(height)

    # Boilerplate
    layout = QtWidgets.QHBoxLayout()
    layout.addWidget(btn1)
    layout.addWidget(btn2)
    container = QtWidgets.QWidget()
    container.setLayout(layout)
    container.show()
    sys.exit(app.exec_())

Upvotes: 1

Views: 1615

Answers (1)

S. Nick
S. Nick

Reputation: 13651

void QWidget::resize(int w, int h)

This corresponds to resize(QSize(w, h)). Note: Setter function for property size.

import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import QSize
import random

class MyButton(QtWidgets.QPushButton):
    def __init__(self):
        super().__init__("BUTTON1")

    def sizeHint(self):
        return QSize(100, 100)

if __name__=='__main__':

    app = QtWidgets.QApplication(sys.argv)

    # Button with sizeHint 100x100
    btn1 = MyButton()
    btn1.resize(btn1.sizeHint())                            # <========

# There is a chance this button will be sized differently than its sizeHint wants
#    if random.randint(0, 1):
#        btn1.setFixedHeight(200)
#        print("btn1 2->", btn1.size())

    # This line works if btn1.setFixedHeight was called, but otherwise gives the wrong height of 480px
    height = btn1.size().height()

    # I want btn2 to be the same height as btn1
    btn2 = QtWidgets.QPushButton("BUTTON2")
    btn2.setFixedHeight(height)

    # Boilerplate
    layout = QtWidgets.QHBoxLayout()
    layout.addWidget(btn1)
    layout.addWidget(btn2)
    container = QtWidgets.QWidget()
    container.setLayout(layout)
    container.show()
    sys.exit(app.exec_())

enter image description here

Upvotes: 1

Related Questions