Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adjust size after child widget resized in Qt

Tags:

c++

qt

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();

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.

like image 559
lzhang3 Avatar asked Dec 22 '25 04:12

lzhang3


1 Answers

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.

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);
}
like image 164
Kuba hasn't forgotten Monica Avatar answered Dec 23 '25 18:12

Kuba hasn't forgotten Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!