【Y忍冬草】基于moveToThread的多线程

利用moveToThread来实现多线程,直接上代码吧。
界面:
【Y忍冬草】基于moveToThread的多线程_第1张图片

movetothread.h

#ifndef MOVETOTHREAD_H
#define MOVETOTHREAD_H
#include 

class MoveToThread : public QObject
{
    Q_OBJECT
public:
    MoveToThread(QObject *parent = 0);

public slots:
    void callWork();
    void slotWork1();
    void slotWork2();
    void slotWork3();

private:
    QThread *thread;
};

#endif // MOVETOTHREAD_H
movetothread.cpp

#include 
#include 
#include "movetothread.h"

MoveToThread::MoveToThread(QObject *parent) :
    QObject(parent)
{
    thread = new QThread;
    this->moveToThread(thread);
    thread->start();
}

void MoveToThread::callWork()
{
    qDebug() << "callWork :" << QThread::currentThread();
}

void MoveToThread::slotWork1()
{
    qDebug() << "slotWork1: " << QThread::currentThread();
}

void MoveToThread::slotWork2()
{
    qDebug() << "slotWork2: " << QThread::currentThread();
}

void MoveToThread::slotWork3()
{
    qDebug() << "slotWork3: " << QThread::currentThread();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include "movetothread.h"


namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void mainCall();

private:
    Ui::MainWindow *ui;

    MoveToThread *work1;
    MoveToThread *work2;
    MoveToThread *work3;
    MoveToThread *work4;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    work1 = new MoveToThread;
    work2 = new MoveToThread;
    work3 = new MoveToThread;
    work4 = new MoveToThread;


    connect(ui->callBtn, SIGNAL(clicked()), this, SLOT(mainCall()));
    connect(ui->slot1Btn, SIGNAL(clicked()), work2, SLOT(slotWork1()), Qt::QueuedConnection);
    connect(ui->slot2Btn, SIGNAL(clicked()), work3, SLOT(slotWork2()), Qt::QueuedConnection);
    connect(ui->slot3Btn, SIGNAL(clicked()), work4, SLOT(slotWork3()), Qt::QueuedConnection);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::mainCall()
{
    work1->callWork();
}

main.cpp

#include "mainwindow.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

【参考:】
1.http://blog.csdn.net/tadpole_java/article/details/47399529

你可能感兴趣的:(Qt)