Qt moveToThread開啟執行緒的一種方法
阿新 • • 發佈:2018-12-14
#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(); }