在主线程上,可以控制子线程启动,停止,清零
如果子线程启动的话,每一秒钟会向主线程发送一个数字,让主线程更新界面上的数字。
程序截图:
上代码:
main.cpp
1 2 3 4 5 6 7 8 9 10 11 |
#include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); } |
widget.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QLabel> #include <QPushButton> #include "thread.h" 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 // WIDGET_H |
widget.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
#include "widget.h" #include <QVBoxLayout> Widget::Widget(QWidget *parent) : 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(); } |
thread.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#ifndef THREAD_H #define THREAD_H #include <QThread> 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(); }; #endif // THREAD_H |
thread.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include "thread.h" Thread::Thread(QObject *parent) : QThread(parent) { number = 0; } Thread::~Thread() { } void Thread::run() { while(1) { //开启一个死循环,让number每秒自增1,并通过发送UpdateSignal信号通知主界面更新 emit UpdateSignal(number); number++; sleep(1); } } void Thread::ResetSlot() { number = 0; emit UpdateSignal(number); } |
发表评论
要发表评论,您必须先登录。