QThread
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include<QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
void run();
bool Stop;
signals:
void NumberChanged(int);
public slots:
};
#endif // MYTHREAD_H
#ifndef DIALOG_H #define DIALOG_H #include "mythread.h" #include <QDialog> #include<QLabel> namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); MyThread *mThread; private: Ui::Dialog *ui; public slots: void onNumberChanged(int); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); }; #endif // DIALOG_H
#include "dialog.h" #include "ui_dialog.h" #include<QLabel> Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); mThread = new MyThread(this); connect(mThread,SIGNAL(NumberChanged(int)),this, SLOT(onNumberChanged(int))); } Dialog::~Dialog() { delete ui; } void Dialog::onNumberChanged(int Number) { ui->label->setText(QString::number(Number)); } void Dialog::on_pushButton_clicked() { //started mThread->start(); } void Dialog::on_pushButton_2_clicked() { mThread->Stop = true; }
#include "dialog.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Dialog w; w.show(); return a.exec(); }
#include "mythread.h" #include <QThread> MyThread::MyThread(QObject *parent) : QThread(parent) { } void MyThread::run() { this->Stop = false; for(int i = 0; i < 10000;i++) { QMutex mutex; mutex.lock(); if(this->Stop) break; mutex.unlock(); emit NumberChanged(i); this->msleep(1000); } }