Qt QWidget :: minimumSizeHint delay [英] Qt QWidget::minimumSizeHint delay

查看:225
本文介绍了Qt QWidget :: minimumSizeHint delay的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用spoiler编写对话框。当我显示/隐藏一些元素时,表单必须调整大小以匹配她的内容。但我注意到minimumSizeHint工程有一些延迟。例如我写了以下对话框代码:

I want to write dialog with "spoiler". When I show/hide some elements, the form must resize to match her content. But I noticed that minimumSizeHint works with some delay. For example I wrote following dialog code:

dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>

class Dialog : public QDialog {
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);

private:
    QPushButton *button1, *button2, *button3;
    void adjust();
};

#endif // DIALOG_H

dialog.cpp

dialog.cpp

#include <QVBoxLayout>
#include <QPushButton>
#include <QTimer>

#include "dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent) {
    QVBoxLayout *layout = new QVBoxLayout;
    button1 = new QPushButton("bad method", this);
    button2 = new QPushButton("working method", this);
    button3 = new QPushButton("indent", this);
    layout->addWidget(button1);
    layout->addWidget(button2);
    layout->addWidget(button3);
    setLayout(layout);

    connect(button1, &QPushButton::pressed, [=]() {
        button3->setVisible(!button3->isVisible());

        adjust();
    });

    connect(button2, &QPushButton::pressed, [=]() {
        button3->setVisible(!button3->isVisible());

        QTimer *timer = new QTimer(this);
        connect(timer, &QTimer::timeout, [=](){ adjust(); });
        timer->setSingleShot(true);
        timer->start(0);
    });
}

void Dialog::adjust() {
    resize(width(), minimumSizeHint().height());
}

当按下button1时,表单与内容不匹配,按下button2,形式紧紧匹配她的内容。
如何实现结果为按button2没有计时器和其他解决方法?为什么button1不工作?

When pressed button1, the form isn't match her content tightly, but when pressed button2, the form tightly match her content. How to achieve results as pressing button2 without timers and other workarounds? Why button1 isn't work?

推荐答案

考虑在事件循环中处理某些事件之前不计算最小大小。如果您不想使用计时器,一个解决方法是在按钮隐藏或显示后,对事件循环进行一些迭代,然后调整大小。

Consider that the minimum size is not computed until some events are processed in the event loop. If you don't want to use a timer, one workaround is to process the event loop for some iterations after the button is hidden or made visible, and then adjust size.

如下:

        button3->setVisible(!button3->isVisible());

        for(int i=0;i<10;i++)
           qApp->processEvents();

        adjust();

更好的解决方案是调用 QLayout :: activate c $ c> before resizing:

A better solution is to call QLayout::activate() before resizing:

        button3->setVisible(!button3->isVisible());

        layout->activate();

        adjust();

activate()强制重新计算布局大小提示。

activate() forces your layout to recalculate the size hint.

这篇关于Qt QWidget :: minimumSizeHint delay的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆