【问题标题】:How to get a signal when the widget size changes小部件大小更改时如何获取信号
【发布时间】:2018-01-05 18:54:20
【问题描述】:

当小部件 (MyForm) 的大小发生变化时,我需要执行操作。

当小部件的大小发生变化时是否会发出信号? (我在文档中找不到它)。

我需要这样做:

#include "myform.h"
#include "ui_myform.h"

MyForm::MyForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyForm)
{
    ui->setupUi(this);

    connect(this, SIGNAL(sizeChanged()), this, SLOT(refresh()));
}

MyForm::~MyForm()
{
    delete ui;
}

void MyForm::refresh()
{
    ui->label->setText( QString::number(this->width()) + ", " + QString::number(this->height()));
}

当小部件尺寸发生变化时,它会“调用”refresh 函数,该函数使用当前的widthheight 更新标签。 注意:这只是一个可以轻松复制的示例。


当然我可以使用QTimer,例如:

#include "myform.h"
#include "ui_myform.h"

MyForm::MyForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyForm)
{
    ui->setupUi(this);

    timer_ = new QTimer(this);
    connect(timer_, SIGNAL(timeout()), this, SLOT(refresh()));

    timer_->start(100);
}

MyForm::~MyForm()
{
    delete ui;
}

void MyForm::refresh()
{
    ui->label->setText( QString::number(this->width()) + ", " + QString::number(this->height()));
}

但我认为这不是最好的解决方案。

注意:我使用的是 Qt 5.3。

【问题讨论】:

标签: c++ qt qt5


【解决方案1】:

不必创建信号,您只需覆盖resizeEvent() 并从该方法调用刷新:

*.h

protected:
    void resizeEvent(QResizeEvent *event);

*.cpp

void MyForm::resizeEvent(QResizeEvent *event)
{
    refresh();
    QWidget::resizeEvent(event);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2021-09-10
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    相关资源
    最近更新 更多