#include <QCoreApplication>
#include "mythread.h"
#include "worker.h"
#include <QTimer>
int main(int argc, char* argv[])
{
QCoreApplication app(argc, argv);
#if 0
MyThread thread;
thread.start();
thread.foo();
#endif
qDebug() << "main thread is"<<QThread::currentThread();
Worker* worker = new Worker();
QTimer* timer = new QTimer;
QObject::connect(timer, SIGNAL(timeout()), worker, SLOT(doWork()));
timer->setInterval(1000);
timer->start();
return app.exec();
}
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QDebug>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
void foo()
{
qDebug() << QThread::currentThread();
}
void run()
{
foo();
qDebug() << "thread is run";
}
signals:
public slots:
};
#endif // MYTHREAD_H
#include "mythread.h"
MyThread::MyThread(QObject *parent) :
QThread(parent)
{
}
#ifndef WORKER_H
#define WORKER_H
#include <QObject>
#include <QThread>
#include <QDebug>
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker(QObject *parent = 0);
QThread _thread;
bool event(QEvent *ev)
{
qDebug() << "event:"<<QThread::currentThread();
return QObject::event(ev);
}
signals:
public slots:
void doWork()
{
// do ......
qDebug() << QThread::currentThread();
}
};
#endif // WORKER_H
#include "worker.h"
Worker::Worker(QObject *parent) :
QObject(parent)
{
// this->moveToThread(&_thread);
_thread.start();
connect(&_thread, SIGNAL(finished()), this, SLOT(deleteLater()));
}