//main 函数内容
#include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }
//Widget 内容
#include "widget.h" #include "ui_widget.h" #include <QThread> #include <QDebug> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); falg_stop_or_action = 0; ui->lcdNumber->display(20); // not zhiding father pthread_my = new mypthread; thread = new QThread(this); pthread_my->moveToThread(thread); //这个地方 是精髓
//这个是线程函数在执行的时候 发来一个信号 主要是来看现象 connect(pthread_my,&mypthread::mysignal,this,&Widget::dealsingnal); connect(&timer,&QTimer::timeout,this,&Widget::dealtimer);
//主动发信号去调用 线程函数 connect(this,&Widget::startpthread,pthread_my,&mypthread::myTimerout); } Widget::~Widget() { delete ui; } void Widget::on_pushButton_send_stop_clicked() { pthread_my->setFlag(true); if(falg_stop_or_action == 0) { falg_stop_or_action = 1; timer.start(1000); } qDebug()<< "pthread ID" <<thread->currentThread(); //Start pthread thread->start(); emit startpthread(); } void Widget::on_pushButton_2_clicked() {
//停止按钮的 槽函数 falg_stop_or_action = 0; timer.stop();
pthread_my->setFlag(false);
//下面这两部 少了啥都不能调用这个线程 thread->quit(); thread->wait(); } void Widget::dealsingnal() {
//线程发来信号 打印一下 qDebug()<< "pthread aciton" ; } void Widget::dealtimer() {
//用了一个LCD的计时器 一样的东西来观察现象 static int i = 0; ui->lcdNumber->display(++i); }
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QTimer> #include "mypthread.h" namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); void dealsingnal(); void dealtimer(); signals: void startpthread(); private slots: void on_pushButton_send_stop_clicked(); void on_pushButton_2_clicked(); private: Ui::Widget *ui; QTimer timer; mypthread * pthread_my; QThread * thread; // 0 stop 1 action char falg_stop_or_action; }; #endif // WIDGET_H
// mypthread 内容
#include "mypthread.h" #include <QThread> #include <QDebug> mypthread::mypthread(QObject *parent) : QObject(parent) { isstop = true; } void mypthread::myTimerout() { qDebug()<< "pthread aciton"<<QThread::currentThread(); while(isstop) { QThread::sleep(1); emit mysignal(); } } void mypthread::setFlag(bool s) { isstop = s; }
#ifndef MYPTHREAD_H #define MYPTHREAD_H #include <QObject> class mypthread : public QObject { Q_OBJECT public: explicit mypthread(QObject *parent = 0); void myTimerout(); void setFlag(bool s); signals: void mysignal(); public slots: private: bool isstop; }; #endif // MYPTHREAD_H