close

 

 

前幾天受到了點挫折,不過也因為這樣才讓自己了解自己對事情的理解還有待加強,

很多東西會用但不會講,會講但是講不好,透過這次的挫折使自己更了解自己,

這也算是不錯的意外收穫。

 

沉澱了幾天,也站起來了,畢竟我認為身為一個專業的工程師,

每天都被"擊敗",是一件很正常的事情,重要的是,被擊敗後的站起來,

這更難能可貴。

 

 

好拉,我們就繼續來分享Qt 吧 !

 

 

 

 

 

Qt - Timer 

 

Step1. Creat a new class , call "mytimer"

mytimer.h 

#ifndef MYTIMER_H
#define MYTIMER_H
 
#include <QtCore>
 
 
class MyTimer : public QObject
{
    Q_OBJECT
public:
    MyTimer();
 
    QTimer *timer;
 
public slots:
    void MySlot();
 
};
 
#endif // MYTIMER_H
 

 

mytimer.cpp

#include "mytimer.h"
#include <QtCore>
#include <QDebug>
 
 
MyTimer::MyTimer()
{
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()) ,this, SLOT(MySlot()));
    timer->start(1000);
}
 
void MyTimer::MySlot(){
 
    qDebug () << "Timer executed";
 
}
 

main.cpp

#include <QCoreApplication>
 
#include "mytimer.h"
 
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
 
    MyTimer mTimer;
 
 
    return a.exec();
}
 

 

 

 

 

 

 

Qt- thread

mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H
 
#include <QtCore>
 
 
class MyThread : public QThread
{
public:
    MyThread();
    void run();
    QString name;
    bool stop;
 
};
 
#endif // MYTHREAD_H
 

 

mythread.cpp

#include "mythread.h"
#include <QtCore>
#include <QDebug>
 
MyThread::MyThread()
{
 
}
 
void MyThread::run()
{
    qDebug()<< this->name << " Running";
 
    for (int i =0 ; i < 1000 ; i++)
    {
        QMutex mutex;
        mutex.lock();
        if (this->stop)
        {
            break;
        }
        mutex.unlock();
        this->sleep(1);
        qDebug()<< this->name << " Running" << i;
    }
 
}
 

 

main.cpp

#include <QCoreApplication>
#include "mythread.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
    MyThread mThread1;
    mThread1.name = "m_thread_1";
 
 
    MyThread mThread2;
    mThread2.name = "m_thread_2";
 
 
    MyThread mThread3;
    mThread3.name = "m_thread_3";
 
 
    mThread1.start();
    //mThread2.start();
    //mThread3.start();
 
    mThread1.stop = true;
 
 
    return a.exec();
}
 

 

 

 

 

 

arrow
arrow
    文章標籤
    Qt timer thread
    全站熱搜

    Eric 發表在 痞客邦 留言(0) 人氣()