SHARE
TWEET

Untitled

a guest Jul 22nd, 2019 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5. #include <QThread>
  6.  
  7. class Worker : public QObject {
  8.     Q_OBJECT
  9.     int i = 0;
  10. public:
  11.     Worker() : QObject() { }
  12. signals:
  13.     void finished(int i);
  14. public slots:
  15.     void process();
  16. };
  17.  
  18. class Controller : public QObject {
  19.     Q_OBJECT
  20.     Worker *w;
  21.     QThread *thr;
  22. public:
  23.     Controller(QObject *parent = nullptr) : QObject(parent) { }
  24. private slots:
  25.     void middleFinish(int i);
  26. public slots:
  27.     void start();
  28. signals:
  29.     void finished(int i);
  30. };
  31.  
  32. namespace Ui {
  33. class MainWindow;
  34. }
  35.  
  36. class MainWindow : public QMainWindow
  37. {
  38.     Q_OBJECT
  39. public:
  40.     explicit MainWindow(QWidget *parent = nullptr);
  41.     ~MainWindow();
  42. private:
  43.     Ui::MainWindow *ui;
  44.     Controller _c;
  45. };
  46.  
  47. #endif // MAINWINDOW_H
  48.      
  49. #include "mainwindow.h"
  50. #include "ui_mainwindow.h"
  51.  
  52. #include <QDebug>
  53.  
  54. void Worker::process() { finished(++i); }
  55.  
  56. void Controller::start() {
  57.     thr = new QThread;
  58.     w = new Worker;
  59.     w->moveToThread(thr);
  60.     connect(thr, &QThread::started, w, &Worker::process);
  61.     connect(w, &Worker::finished, this, &Controller::middleFinish);
  62.     thr->start();
  63. }
  64. void Controller::middleFinish(int i) {
  65.     qDebug() << "middleFinish" << i;
  66.     disconnect(w, &Worker::finished, this, &Controller::middleFinish);
  67.     connect(w, &Worker::finished, this, &Controller::finished);
  68.     connect(w, &Worker::finished, thr, &QThread::quit);
  69.     connect(w, &Worker::finished, w, &Worker::deleteLater);
  70.     connect(thr, &QThread::finished, thr, &QThread::deleteLater);
  71.     thr->start();
  72. }
  73.  
  74. MainWindow::MainWindow(QWidget *parent)
  75.     : QMainWindow(parent), ui(new Ui::MainWindow) {
  76.     ui->setupUi(this);
  77.     connect(&_c, &Controller::finished, this, [] (int i) { qDebug() << "finish" << i; });
  78.     _c.start();
  79. }
  80.  
  81. MainWindow::~MainWindow() { delete ui; }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top