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

问题描述 投票:0回答:1

我试图通过检查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_())
python pyqt size pyqt5
1个回答
1
投票

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

这对应于调整大小(QSize(w,h))。注意:属性大小的Setter函数。

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

© www.soinside.com 2019 - 2024. All rights reserved.