QT小例子GUI(主)執行緒與子執行緒之間的通訊
阿新 • • 發佈:2019-02-15
在主執行緒上,可以控制子執行緒啟動,停止,清零
如果子執行緒啟動的話,每一秒鐘會向主執行緒傳送一個數字,讓主執行緒更新介面上的數字。
- #ifndef TQT_H_
- #define TQT_H_
- #include <QtGui>
- #include <QtCore>
- class Thread : public QThread
- {
- Q_OBJECT
- private:
- int number;
- protected:
- void run();
- public:
- Thread(QObject *parent=0);
-
~Thread();
- signals:
- void UpdateSignal(int num);
- public slots:
- void ResetSlot();
- };
- class Widget : public QWidget
- {
- Q_OBJECT
- private:
- QLabel *label;
- QPushButton *startButton;
- QPushButton *stopButton;
- QPushButton *resetButton;
- Thread *myThread;
-
int number;
- public:
- Widget(QWidget *parent = 0);
- ~Widget();
- signals:
- void ResetSignal();
- public slots:
- void ClearSlot();
- void StartSlot();
- void StopSlot();
- void UpdateSlot(int num);
- };
- #endif
- //tqt.cpp
- #include "tqt.h"
- #include <assert.h>
-
#include <windows.h>
- Thread::Thread(QObject *parent)
- {
- number = 0;
- }
- Thread::~Thread()
- {
- }
- void Thread::run()
- {
- while(1)
- {
- emit UpdateSignal(number);
- number++;
- sleep(1);
- }
- }
- void Thread::ResetSlot()
- {
- number = 0;
- emit UpdateSignal(number);
- }
- Widget::Widget(QWidget *parent)
- {
- startButton = new QPushButton("start");
- stopButton = new QPushButton("stop");
- resetButton = new QPushButton("reset");
- label = new QLabel("empty");
- myThread = new Thread;
- QVBoxLayout *layout = new QVBoxLayout;
- layout->addWidget(label);
- layout->addWidget(startButton);
- layout->addWidget(stopButton);
- layout->addWidget(resetButton);
- setLayout(layout);
- connect(stopButton, SIGNAL(clicked()),
- this, SLOT(StopSlot()));
- connect(startButton, SIGNAL(clicked()),
- this, SLOT(StartSlot()));
- connect(resetButton, SIGNAL(clicked()),
- this, SLOT(ClearSlot()));
- connect(myThread, SIGNAL(UpdateSignal(int)),
- this, SLOT(UpdateSlot(int)));
- connect(this, SIGNAL(ResetSignal()),
- myThread, SLOT(ResetSlot()));
- setWindowTitle("Thread Test");
- resize(200, 200);
- myThread->start();
- }
- Widget::~Widget()
- {
- }
- void Widget::StartSlot()
- {
- myThread->start();
- }
- void Widget::StopSlot()
- {
- myThread->terminate();
- }
- void Widget::UpdateSlot(int num)
- {
- label->setText(QString::number(num));
- }
- void Widget::ClearSlot()
- {
- emit ResetSignal();
- }
- //main.cpp
- #include <QtGui>
- #include "tqt.h"
- int main(int argc,char **argv)
- {
- QApplication app(argc, argv);
- Widget *widget = new Widget;
- widget->show();
- return app.exec();
- }
FROM: http://blog.csdn.net/slj_win/article/details/6856428