您的位置:首页 > 编程语言 > Qt开发

a demo for how to use QThread

2015-09-12 14:48 483 查看
/*******************************************************************
*                 a demo for how to use QThread
* 声明:
*     这是一个简单的QThread使用模板,对于应付简单的程序来说,
* 还是足够了。
*
*                           2015-9-12 阴 深圳 南山平山村 曾剑锋
******************************************************************/
cat thread.h
#ifndef THREAD_H
#define THREAD_H

#include <QThread>

class Thread : public QThread
{
Q_OBJECT
public:
explicit Thread(QObject *parent = 0);

signals:
void msg(QString str);
public slots:
void run();
void stop();

private:
bool running;
};

#endif // THREAD_H

cat thread.c
#include "thread.h"

Thread::Thread(QObject *parent) :
QThread(parent)
{
running = true;
}

void Thread::run()
{
int nbytes;
int len;
struct can_frame frame;
struct sockaddr_can addr;
char buf[10];

while(running)
{
QThread::msleep(100);
/**
* this was very important sametime for receive data
*/
if (running) {
emit msg(QString(buf));
}
}
}

void Thread::stop()
{
running = false;
}

cat mainwindow.c
......
/**
* how to stop a Qt thread
*/
if ( thread != NULL ) {
thread->stop();
thread->wait();
thread->deleteLater();
}
......
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: