Qt moveToThread开启线程的一种方法

#ifndef MYMOVETOTHREAD_H
#define MYMOVETOTHREAD_H
#include <QObject>
#include <QThread>
#include <QDebug>

class Worker:public QObject
{
    Q_OBJECT
public:
    Worker(){}
    ~Worker(){}
public slots:
    void first()
    {
        qDebug()<<QThread::currentThreadId();
    }
    void second()
    {
        qDebug()<<QThread::currentThreadId();
    }
    void three()
    {
        qDebug()<<QThread::currentThreadId();
    }
};



#endif // MYMOVETOTHREAD_H
#include <QDateTime>
#include <QDebug>
#include <QThread>
#include <QDir>
#include "mymovetothread.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QString strTemp = QDir::tempPath();
    qDebug()<<strTemp;
    myWork = new Worker;

    connect(ui->firstButton,SIGNAL(clicked(bool)),myWork,SLOT(first()),Qt::QueuedConnection);
    connect(ui->secondButton,SIGNAL(clicked(bool)),myWork,SLOT(second()),Qt::QueuedConnection);
    connect(ui->threeButton,SIGNAL(clicked(bool)),myWork,SLOT(three()),Qt::QueuedConnection);

    QThread* thread = new QThread;
    myWork->moveToThread(thread);
    thread->start();

}

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

void MainWindow::on_startButton_clicked()
{
    if(!thread.isRunning())
    {
        qDebug()<<"thread is not running";
    }
    thread.start();
    ui->stopButton->setEnabled(true);
    ui->startButton->setEnabled(false);
}


void MainWindow::on_stopButton_clicked()
{
    if(thread.isRunning())
    {
        qDebug()<<"thread is running";
        thread.stop();
        ui->stopButton->setEnabled(false);
        ui->startButton->setEnabled(true);
    }
}



void MainWindow::on_selfButton_clicked()
{
    qDebug() << QThread::currentThreadId();

}

void MainWindow::on_exitButton_clicked()
{
    close();
}

猜你喜欢

转载自blog.csdn.net/qq_24127015/article/details/84281403
今日推荐