使用PyQt4调整对话框的大小

ils*_*tam 9 python qt pyqt pyqt4

我有这个代码示例:

import sys
from PyQt4.QtGui import (QApplication, QHBoxLayout, QVBoxLayout, QDialog,
                                          QFrame, QPushButton, QComboBox)

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        moreButton = QPushButton('moreButton')
        moreButton.setCheckable(True)
        resizeButton = QPushButton('Resize')
        combo = QComboBox()
        combo.addItems(['item1', 'item2'])

        layout1 = QHBoxLayout()
        layout1.addWidget(moreButton)
        layout1.addWidget(resizeButton)

        layout2 = QHBoxLayout()
        layout2.addWidget(combo)
        self.frame = QFrame()
        self.frame.setLayout(layout2)
        self.frame.hide()

        layout3 = QVBoxLayout()
        layout3.addLayout(layout1)
        layout3.addWidget(self.frame)

        moreButton.toggled.connect(self.frame.setVisible)
        moreButton.clicked.connect(self.method)
        resizeButton.clicked.connect(self.method)

        self.setLayout(layout3)
        self.resize(630, 50)

    def method(self):
        if self.frame.isVisible():           
            self.resize(630, 150)
        else:
            self.resize(630, 250)

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
Run Code Online (Sandbox Code Playgroud)

我运行它,当moreButton点击时,ComboBox出现或消失.Dialog的大小也会发生变化.但是,如果我将方法更改为:

def method(self):
    if self.frame.isVisible():           
        self.resize(630, 150)
    else:
        self.resize(630, 50)
Run Code Online (Sandbox Code Playgroud)

(为了在隐藏组合时设置初始大小)调整大小不起作用.但是,如果我单击resizeButton - 它连接到相同的方法 - 调整大小正常工作.

我知道还有其他方法可以实现这样的结果(例如layout.setSizeConstraint(QLayout.SetFixedSize)),但我想明确声明大小.

我究竟做错了什么?

Ava*_*ris 6

我的猜测是,QDialog在你隐藏东西之后你有时间重新调整它的大小之前你试图调整大小.因此,当时resize称它有一个minimumSize确保按钮和组合框可见.当你在一段时间后调用它,它现在已经正确miminumSize并且响应正确.

快速修复是minimumSize在调整大小之前手动覆盖:

def method(self):
    if self.frame.isVisible():
        # uncomment below, if you like symmetry :)
        # self.setMinimumSize(630, 150)
        self.resize(630, 150)
    else:
        self.setMinimumSize(630, 50)
        self.resize(630, 50)
Run Code Online (Sandbox Code Playgroud)

但是,如果我要解决这个问题,我只需要管理调整大小以适应布局和使用sizeConstraint.无论如何,这就是这些布局.