Total Articles 180
[MyThread.h]
#include <QObject> #include <boost/thread.hpp> class MyThread : public QObject { Q_OBJECT public: MyThread(); virtual ~MyThread(); public: boost::uint32_t interval; bool active; public: bool open(); bool close(); protected: boost::thread* t; static void threadFunc(MyThread* thread); signals: void onTimer(int n); };
[MainThread.cpp]
#include "MyThread.h" void Sleep(boost::uint32_t milliseconds) { boost::posix_time::milliseconds msec(milliseconds); boost::this_thread::sleep(msec); } MyThread::MyThread() { interval = 1000; active = false; t = NULL; } MyThread::~MyThread() { if (t == NULL) { close(); } } bool MyThread::open() { if (active) return false; active = true; t = new boost::thread(threadFunc, this); return true; } bool MyThread::close() { if (!active) return false; active = false; t->join(); delete t; return true; } void MyThread::threadFunc(MyThread* thread) { int n = 0; while (thread->active) { Sleep(thread->interval); emit thread->onTimer(n); n++; } }
[mainwindow.h]
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "MyThread.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); public: MyThread myThread; private slots: void onTimer(int n); private slots: void on_btnOpen_clicked(); void on_btnClose_clicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
[mainwindow.cpp]
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QObject::connect(&myThread, SIGNAL(onTimer(int)), this, SLOT(onTimer(int))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::onTimer(int n) { ui->label->setText(QString::number(n)); } void MainWindow::on_btnOpen_clicked() { myThread.open(); } void MainWindow::on_btnClose_clicked() { myThread.close(); }
[download]