在Qt中调整子窗口小部件的大小后调整大小 [英] adjust size after child widget resized in Qt

查看:83
本文介绍了在Qt中调整子窗口小部件的大小后调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个非常简单的测试程序,当单击按钮时,GraphicsView将显示图像,并使用网格布局.我希望窗口大小根据图像大小自动调整.该代码类似于

I'm writing a very simple test program that when a push button is clicked, a GraphicsView will display an image, a grid layout is used. I want the window size adjust automatically according to the image size. The code is similar to

// load image and setup scene
// ...
ui->graphicsView->show();
ui->graphicsView->updateGeometry();

// adjustSize();
adjustSize();

问题是,当调用 adjustSize()时,窗口无法调整大小以正确大小,因此我必须两次调用 adjustSize()或显示一个在调用 adjustSize()将窗口调整为正确大小之前,请先使用QMessageBox.而且btw resize(sizeHint())给出相同的结果

The problem is that when adjustSize() is called, the window doesn't resize to correct size, and I have to call adjustSize() twice or display a QMessageBox before calling adjustSize() to resize the window to correct size. And btw resize(sizeHint()) gives the same result

我想知道为什么会发生这种情况,有没有一种优雅的方法可以正确地做到这一点?非常感谢.

I wonder why this is happening and is there an elegant way to do it correctly? Many thanks.

推荐答案

调用 adjustSize()时,以前的调用都没有任何可见的效果,因为这些效果仅在事件循环已运行.多次调用它的操作可能是间接地从事件循环中耗尽了一些事件,就像通过 exec()或静态方法显示 QMessageBox 一样.

When you call the adjustSize(), none of the previous calls had any visible effects, since those effects are caused only when the event loop has been run. What you do by calling it multiple times is probably indirectly draining some events from the event loop, same with displaying a QMessageBox via exec() or a static method.

您需要从事件循环中调用 adjustSize .由于它不可调用,因此需要在小部件类(或辅助类)中做到这一点.

You need to invoke adjustSize from the event loop. Since it is not invokable, you need to make it so in your widget class (or in a helper class).

// Interface
class MyWidget : public QWidget {
  Q_OBJECT
  Q_INVOKABLE void adjustSize() { QWidget::adjustSize(); }
  ...
};

// Implementation
void MyWidget::myMethod() {
  // ...
  ui->graphicsView->show();
  ui->graphicsView->updateGeometry();

  QMetaObject::invokeMethod(this, "adjustSize", Qt::QueuedConnection);
}

这篇关于在Qt中调整子窗口小部件的大小后调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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