QT之movetothread
之前写了个线程是通过重写Thread的run方法来实现的,但如今出现了以一个更加灵活的创建线程的方法,那就是movetothread方法。
movetothread的意思就是把某个东西移动到线程里,然后通过信号与槽的方式实现调用。但是使用movetothread时,必须是继承QObject类的类。
具体使用:
mythread.h文件
#ifndef MYTHREAD_H #define MYTHREAD_H #include <QObject> #include "mythread.h" class mythread : public QObject { Q_OBJECT public: explicit mythread(QObject *parent = nullptr); void print(); signals: void getData(int i); public slots: }; #endif // MYTHREAD_H
mythread.cpp
#include "mythread.h" #include <QDebug> mythread::mythread(QObject *parent) : QObject(parent) { } void mythread::print() { for(int i = 0; i<10; i++) { emit getData(i); } }
thread.h
#ifndef THREAD_H #define THREAD_H #include <QObject> #include "mythread.h" class thread : public QObject { Q_OBJECT public: explicit thread(QObject *parent = nullptr); signals: public slots: void sendData(const int &a); }; #endif // THREAD_H
thread.cpp
#include "thread.h" #include <QDebug> thread::thread(QObject *parent) : QObject(parent) { } void thread::sendData(const int &a) { qDebug()<<"xxx"; qDebug()<<a; }
最重要的代码
main.cpp
#include <QCoreApplication> #include "mythread.h" #include "thread.h" #include <QThread> #include <QDebug> #include <QTimer> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QThread mytcp, th; mythread mtd; //实例化 thread td; QObject::connect(&mtd, SIGNAL(getData(int)), &td, SLOT(sendData(const int &))); //先连接信号与槽,后发送信号函数 mtd.moveToThread(&mytcp); mytcp.start(); td.moveToThread(&th); th.start(); mtd.print(); //调用信号 return a.exec();
运行结果: