如何正常的退出,释放线程和线程槽
Worker不能设置parent
A *a = new A;
QThread *t = new QThread;
a->moveToThread(t);
connect(t, SIGNAL(started()), a, SLOT(start()));
connect(a, SIGNAL(finish()), a, SLOT(deleteLater()));
connect(a, SIGNAL(destroyed()), t, SLOT(quit()));
connect(t, SIGNAL(finished()), t, SLOT(deleteLater()));
#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();
}