Qt Button 强制停止循环

问题描述 投票:0回答:1

在 QObject 子类中,我有一个在无限循环中检查互联网连接的函数:

void S3Downloader::downloadFile(const QString &bucketFilePath) {
        ...
        while (!checkInternetConnection()) {
            QThread::sleep(1);
            qDebug() << "Waiting for the Internet connection";
        }

我想要一个按钮来强制停止应用程序。但是当我处于循环中时,应用程序不会停止:

void PlayWindow::onCloseButtonClicked() {
    const QString exitMessage = "Are you shure you want to exit 2040 World Launcher?";
    if (QMessageBox::Yes == QMessageBox::question(this, "CAUTION", exitMessage, QMessageBox::Yes | QMessageBox::No)) {
        s3Downloader->stop(); // s3Downloader is an instance of S3Downloader class
        PlayWindow::close();
    }
}

c++ qt
1个回答
0
投票

正如评论中所指出的,您的无限循环正在“冻结”您的应用程序(包括 GUI),事件无法处理,因为您的函数不会将控制权交还给事件循环以处理事件。

最好的选择是将

S3Downloader::downloadFile()
执行到一个单独的线程中,这样它就不会阻塞您的应用程序。

如果不这样做,最后的解决方案是将

QThread::sleep()
调用替换为手动强制处理事件。

为此目的,您可以编写如下函数:

void wait_s(unsigned int s)
{
    QTime die_time = QTime::currentTime().addSecs(s);
    while(QTime::currentTime() < die_time)
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

或者(更好):

void wait_s(unsigned int s)
{
    QEventLoop loop;
    QTimer::singleShot(s*1000, &loop, &QEventLoop::quit);
    loop.exec();
}

您可以将

QThread::sleep(1);
替换为
wait_s(1);
,它应该来自。

© www.soinside.com 2019 - 2024. All rights reserved.