main.cpp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
メインウィンドウ.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
cThread = new QThread(this);
cObject = new MyObject();
cObject->moveToThread(cThread);
QObject::connect(ui->pushButton_3, SIGNAL(clicked()),
this, SLOT(close())
);
QObject::connect(cThread, SIGNAL(started()),
cObject, SLOT(doWork())
);
QObject::connect(ui->pushButton_4, SIGNAL(clicked()),
this, SLOT(runThreadSlot())
);
QObject::connect(cThread, SIGNAL(finished()),
cThread, SLOT(deleteLater())
);
QObject::connect(cThread, SIGNAL(finished()),
cObject, SLOT(deleteLater())
);
QObject::connect(cObject, SIGNAL(setStatusBarSignal(QString)),
this, SLOT(setStatusBarSlot(QString))
);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::runThreadSlot()
{
cThread->start();
}
void MainWindow::setStatusBarSlot(QString text)
{
ui->statusBar->showMessage(text);
}
myobject.cpp:
#include "myobject.h"
MyObject::MyObject(QObject *parent) :
QObject(parent)
{
}
void MyObject::doWork()
{
emit setStatusBarSignal(QString::number((qint32) QThread::currentThreadId()));
QThread::currentThread()->quit();
return;
}
メインウィンドウ.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "myobject.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void runThreadSlot();
void setStatusBarSlot(QString);
private:
Ui::MainWindow *ui;
QThread* cThread;
MyObject* cObject;
};
#endif // MAINWINDOW_H
myobject.h:
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <QtCore>
class MyObject : public QObject
{
Q_OBJECT
public:
explicit MyObject(QObject *parent = 0);
signals:
void setStatusBarSignal(QString);
public slots:
void doWork();
};
#endif // MYOBJECT_H
したがって、パターンは次のとおりです。
pushButton_4 clicked() ---> runThreadSlot() ---> cThread start()
スレッドは ですぐQThread::currentThread()->quit();
に終了しますが、再度 pushButton_4 をクリックすると、アプリケーションがクラッシュします。