简体   繁体   English

小部件删除后qt调整大小窗口

[英]qt resize window after widget remove

I'm adding widget in layout 我在布局中添加小部件

ui->horizontalLayout->addWidget(tabwidget);

and qmainwindow resizes itself. 和qmainwindow调整自己的大小。 But then I do 但后来我做到了

tabwidget->setVisible(false);
qs = sizeHint();
resize(qs);

I get the size like tabwidget was not removed from window. 我得到像tabwidget的大小没有从窗口中删除。

I've made new button 我做了新按钮

void MainWindow::on_pushButton_2_clicked()
{
    qs = sizeHint();
    resize(qs);
}

and it gives correct size. 它给出了正确的尺寸。

Seems I need some update function but I can't find it. 似乎我需要一些更新功能,但我找不到它。 Please advice 请指教

This is caused by a long-time internal Qt issue (I remember experiencing it first with Qt3). 这是由长时间的内部Qt问题引起的(我记得先用Qt3体验它)。 The top widget needs to receive an event to truly update its geometry, and know its boundaries. 顶部窗口小部件需要接收事件以真正更新其几何体,并了解其边界。 This event seems to be always received after the resize event generated by the layout, and therefore it is always too late to shrink the widget. 在布局生成的resize事件之后,似乎总是会收到此事件,因此缩小窗口小部件总是为时已晚。

The solution posted in the accepted answer works. 在接受的答案中发布的解决方案有效。 However a simpler solution posted below also works, when added after the layout : 但是,在布局后添加时,下面发布的更简单的解决方案也可以使用:

layout()->removeWidget( widget );

QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );
resize( sizeHint() );

Basically all we need is to let the event loop run and deliver the necessary events so the top widget geometry is updated before resize() is run. 基本上我们需要的是让事件循环运行并提供必要的事件,以便在运行resize()之前更新顶部窗口小部件几何体。

Note that this code might have side effects if you have multiple threads running, or there are events delivered to your slots. 请注意,如果您运行多个线程,或者有事件传递到您的插槽,此代码可能会产生副作用。 Hence it is safer not to have any code in this function after resize(). 因此,在resize()之后不使用此函数中的任何代码更安全。

If the button slot gives you the correct result then you can always call the sizeHint() and subsequent resize() in a slot which is called by a single shot timer: 如果按钮插槽为您提供了正确的结果,那么您始终可以在单个定时器调用的插槽中调用sizeHint()和后续resize()

void MainWindow::fixSize()
{
    QSize size = sizeHint();
    resize(size);
}

void MainWindow::methodWhereIHideTheTabWidget()
{
    tabwidget->setVisible(false);
    QTimer::singleShot(0, this, SLOT(fixSize()));
}

This timer is set to zero delay. 此计时器设置为零延迟。 This means that the slot will be called immediatelly when the program returns to the main loop and hopefully after the internal widget state gets updated. 这意味着当程序返回主循环并且希望在内部窗口小部件状态更新后,将立即调用该槽。 If this doesn't resolve your problem you may try replacing zero with 1. 如果这不能解决您的问题,您可以尝试用1替换零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM