我正在创建一个示例来理解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();
}问题是,当我按下按钮时,计数器工作并在每一秒过去后显示下一个增量,但是主窗口一直没有响应!这不对!我希望我的主窗口能够响应,只有线程才会休眠。我该怎么做?
发布于 2015-06-05 05:18:45
您的代码中有一个错误:您正在创建另一个OddCounter,您将其移动到不同的线程,但是连接到信号的原始oddCounter仍然驻留在主线程中。您应该将代码更改为:
void MainWindow::on_pushButton_clicked()
{
oddCounter->moveToThread( &thread );
thread.start();
emit startOddCounter();
}https://stackoverflow.com/questions/30658789
复制相似问题