a demo for how to use QThread

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

 

posted on 2015-09-12 14:48  zengjf  阅读(538)  评论(0编辑  收藏  举报

导航