问题
写这个demo的意图是想验证Qt的线程在sleep的情况下能否正常处理其他线程发过来的信号。
验证代码
例子很简单。线程sleep 10分钟,点击主窗口按钮,发送命令,看线程是否能够响应。代码如下:
线程代码:
threadtest.h
#ifndef THREADTEST_H
#define THREADTEST_H
#include <QThread>
class threadtest : public QThread
{
Q_OBJECT
public:
explicit threadtest(QObject*parent = 0);
protected:
void run();
private:
bool m_run;
public slots:
void on_button_clicked();
};
#endif // THREADTEST_H
threadtest.cpp
#include "threadtest.h"
#include <QtCore/QDebug>
threadtest::threadtest(QObject *parent) : m_run(false),
QThread(parent)
{
}
void threadtest::run()
{
m_run = true;
while(m_run)
{
qDebug()<<"wait";
sleep(600);
}
}
void threadtest::on_button_clicked()
{
qDebug()<<"buttonclicked";
}
界面代码
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtGui/QPushButton>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget*parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QPushButton *m_btn;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "threadtest.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_btn = new QPushButton(tr("button clicked"),this);
m_btn->setGeometry(20,20,100,25);
threadtest *t = new threadtest();
connect(m_btn,SIGNAL(clicked()),t,SLOT(on_button_clicked()));
t->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
运行结果
QDateTime("周五六月 14 09:45:39 2013") wait
QDateTime("周五六月 14 09:45:45 2013") button clicked
QDateTime("周五六月 14 09:45:46 2013") button clicked
QDateTime("周五六月 14 09:45:46 2013") button clicked
QDateTime("周五六月 14 09:45:47 2013") button clicked
QDateTime("周五六月 14 09:45:47 2013") button clicked
QDateTime("周五 六月 14 09:45:482013") button clicked
结论
Qt线程在sleep的情况下依然可以接收处理来自其他线程的信号