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();

 

 

 

 運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM