如何在Qt工作线程睡眠

How to sleep in a worker thread in Qt?

本文关键字:线程 工作 Qt      更新时间:2023-10-16

我正在创建一个示例来理解Qt中的线程,并希望我的工作线程在每个增量之间睡眠1秒,以便我可以看到调试输出。但是休眠使我的主GUI线程无响应。

这是我在OddCounter类中的槽函数。

void OddCounter::count()
{
    for (int i = 0; i < 10; i++)
    {
        counter += 2;
        qDebug() << counter;
        QThread::sleep( 1 );
    }
}
调用这个线程的主窗口类是:
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    oddCounter = new OddCounter;
    connect(this, SIGNAL(startOddCounter()), evenCounter, SLOT(count()), Qt::QueuedConnection );
}
MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::on_pushButton_clicked()
{
    OddCounter oddCounter;
    oddCounter.moveToThread( &thread );
    thread.start();
    emit startOddCounter();
}

问题是,当我按下按钮,计数器工作,并显示下一个增量后,每一秒钟通过,但主窗口是无响应的所有这些时间!这是不对的!我希望我的主窗口是响应的,只有线程应该睡觉。我怎么做呢?

您的代码中有一个错误:您正在创建另一个OddCounter,您移动到不同的线程,但您的原始oddCounter信号连接到主线程中仍然存在。你应该这样修改你的代码:

void MainWindow::on_pushButton_clicked()
{
    oddCounter->moveToThread( &thread );
    thread.start();
    emit startOddCounter();
}