PyQt size()在显示小部件之前返回错误的大小?

时间:2019-02-20 22:17:50

标签: python pyqt size pyqt5

我正在尝试通过检查button1的大小然后将button2的大小设置为匹配来将button1的大小与button2进行匹配,但是button1上的size()返回不正确的值(640,480),除非我首先show()。但是,如果我在完成布局设置之前就显示了它,那么它会在屏幕上闪烁,而随后的代码我却不想运行。

我该如何解决?

这是一个最小的示例:

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_())

1 个答案:

答案 0 :(得分:1)

  

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

     

这对应于resize(QSize(w,h))。   注意:属性大小的设置函数。

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