繁体   English   中英

如何在Qt的工作线程中睡觉?

[英]How to sleep in a worker thread in Qt?

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

这是OddCounter类中的插槽functoin。

void OddCounter::count()
{
    for (int i = 0; i < 10; i++)
    {
        counter += 2;

        qDebug() << counter;

        QThread::sleep( 1 );
    }
}

调用此线程的mainwindow类是:

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();
}

暂无
暂无

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

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