创建线程
test.h
#ifndef TEST_H
#define TEST_H
#include <QObject>
#include <QTimer>
#include <QDebug>
#include <QDateTime>
#include <QThread>
class test : public QObject
{
Q_OBJECT
public:
explicit test(QObject *parent = nullptr);
signals:
public slots:
void timeout();
void start();
private:
QTimer timer;
};
#endif // TEST_H
test.cpp
#include "test.h"
test::test(QObject *parent)
: QObject{parent}
{
}
void test::timeout()
{
qInfo() << QDateTime::currentDateTime().toString() << QThread::currentThread();
}
void test::start()
{
connect(&timer, &QTimer::timeout, this, &test::timeout);
timer.setInterval(1000);
timer.start();
}
main.cpp
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QTimer>
#include <QSharedPointer>
#include "test.h"
static QSharedPointer<QThread> sptr;
void timeout()
{
if(!sptr.isNull())
{
qInfo() << "Time out - stopping other thread from:" << QThread::currentThread();
sptr.data()->quit();
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qInfo() << "Application Thread:" << a.thread();
qInfo() << "Current Thread:" << QThread::currentThread();
test t;
//test t(&a); //QObject::moveToThread: Cannot move objects with a parent
qInfo() << "Timer Thread:" << t.thread();
QThread thread;
sptr.reset(&thread);
t.moveToThread(&thread);
qInfo() << "Timer Thread:" << t.thread();
t.start();
qInfo() << "Thread State:" << thread.isRunning();
thread.start();
QTimer timer;
timer.singleShot(5000, &timeout);
return a.exec();
}
参考
Qt Core with C++ - Advanced : Creating Threads, Bryan Cairns
版权声明:本文为qq_34762931原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。