myobject.h
#ifndef MYOBJECT
#define MYOBJECT
#include <QObject>
#include <QThread>
#include <QDebug>
#include <QApplication>
class MyObject:public QObject
{
Q_OBJECT
public:
MyObject(){}
~MyObject(){}
public slots:
void first()
{
qDebug() << QThread::currentThreadId();
}
void second()
{
int i = 0;
while(true)
{
if(i++ < 10)
qDebug() << QThread::currentThreadId() << "second()";
else
break;
}
}
void three()
{
for(int i = 0; i< 20000; ++i)
{
qDebug() <<QThread::currentThreadId()<< " -> three -> " << i;
//qApp->processEvents();
}
}
};
#endif // MYOBJECT
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include "myobject.h"
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
~Dialog();
private:
MyObject * my;
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include <QPushButton>
#include <QVBoxLayout>
#include "myobject.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
this->setWindowTitle("moveToThread 事例");
qDebug() << "main" << QThread::currentThreadId();
my = new MyObject;
QPushButton *button1 = new QPushButton("1");
QPushButton *button2 = new QPushButton("2");
QPushButton *button3 = new QPushButton("3");
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(button3);
this->setLayout(layout);
connect(button1,SIGNAL(clicked(bool)),my,SLOT(first()));
connect(button2,SIGNAL(clicked(bool)),my,SLOT(second()));
connect(button3,SIGNAL(clicked(bool)),my,SLOT(three()));
QThread *thread = new QThread;
my->moveToThread(thread);
connect(thread,SIGNAL(finished()),my,SLOT(deleteLater()));
connect(thread,SIGNAL(finished()),thread,SLOT(deleteLater()));
thread->start();
}
Dialog::~Dialog()
{
}
main.cpp
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}