sep*_*far 5 c++ qt qmainwindow qt5
我想一步一步地更新我的QMainWindow.我使用睡眠方法,但我看不到变化.我想每隔3秒看一次变化.
void MainWindow::updateScreen()
{
ui->pushButton1->show();
QThread::sleep(3);
ui->pushButton2->show();
QThread::sleep(3);
ui->pushButton3->show();
QThread::sleep(3);
}
Run Code Online (Sandbox Code Playgroud)
但在9秒后,所有更改立即生效.
你永远不会QThread::sleep()在主线程中使用,因为它阻止GUI被通知事件,因此行为不正确,其他问题正确争论所以我不会全身心投入,我的答案将集中在给你一个解决方案,我认为最适合使用QTimeLine:
const QWidgetList buttons{ui->pushButton1, ui->pushButton2, ui->pushButton3};
QTimeLine *timeLine = new QTimeLine( 3000*buttons.size(), this);
timeLine->setFrameRange(0, buttons.size());
connect(timeLine, &QTimeLine::frameChanged, [buttons](int i){
buttons[i-1]->show();
});
connect(timeLine, &QTimeLine::finished, timeLine, &QTimeLine::deleteLater);
timeLine->start();
Run Code Online (Sandbox Code Playgroud)
我不建议使用,processEvents()因为许多初学者滥用它认为它是神奇的解决方案,例如@cbuchart解决方案是不正确的,因为它解决了直接问题而不是背景,例如尝试在9秒内改变窗口的大小.你可以做到吗?好吧,不是因为QThread :: sleep()阻塞了.
考虑一下在GUI线程中使用的不良做法QThread::sleep(),如果你在某个地方看到它,那就不信任了.
我建议您使用QTimer::singleShot静态方法。
void MainWindow::updateScreen()
{
QTimer::singleShot(3000, [this](){ui->pushButton1->show();});
QTimer::singleShot(6000, [this](){ui->pushButton2->show();});
QTimer::singleShot(9000, [this](){ui->pushButton3->show();});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
149 次 |
| 最近记录: |