I display the width value of the horizontalSpacer , then add the widget to the horizontalLayout , then I display the width value of the horizontalSpacer . The width of the horizontalSpacer should become smaller, but it is not updated. How to make it updated? `

 void SearchForm::on_pushButton_10_clicked() { std::cout << ui->horizontalSpacer->geometry().width() << std::endl; QPushButton* PB = new QPushButton; ui->horizontalLayout->addWidget(PB); std::cout << ui->horizontalSpacer->geometry().width() << std::endl; } 
  • What for? With default sizeType = Expanding, it doesn’t affect anything - Evgeny Shmidt
  • I tried all sizeType. nothing helps - Taras

1 answer 1

The resizing we are interested in is not obvious, but is a consequence of adding a new widget and is processed when drawing. Accordingly, before that the sizes will be unchanged and will change when QLayout analyzes the required sizes of the child widgets.

Thus, for this function, the following occurs:

  1. The width is displayed.
  2. A button is created.
  3. Width is displayed
  4. exit function
  5. event loop
  6. redraw call
    1. width change
    2. drawing

To get the size in the same function, you must additionally call the redraw before you get the new size. To do this, use the QApplication :: processEvents () function, which allows the message handler loop to process new signals, among which is the window update request.

 void SearchForm::on_pushButton_10_clicked() { std::cout << ui->horizontalSpacer->geometry().width() << std::endl; QPushButton* PB = new QPushButton; ui->horizontalLayout->addWidget(PB); QApplication::instance()->processEvents(); std::cout << ui->horizontalSpacer->geometry().width() << std::endl; }