需求: 点击QPushButton按钮,QLabel中的数字,不断累加,一直到999。 做法: 点击QPushButton后,启动线程,线程while循环,不断发送累加的数字回主线程,修改QLabel中的数字 其他: 这种线程的写法是最简单的,全部是Qt封装好的,只需要重写 run 函数就可以了。 主要代码:
// MyThread.h #pragma once #include <QThread> class MyThread : public QThread { Q_OBJECT public: MyThread(QObject *parent=nullptr); ~MyThread(); protected: void run(); signals: void sendNum(int num); };
// MyThread.cpp #include "MyThread.h" MyThread::MyThread(QObject *parent) : QThread(parent) {} MyThread::~MyThread() {} void MyThread::run() { int num = 0; while (num < 1000) { emit sendNum(num); num++; QThread::msleep(5); } }
// QtWidgetsApplication1.cpp #include "MyThread.h" MyWidget::MyWidget(QWidget *parent) : QDialog(parent) { ui.setupUi(this); MyThread* t = new MyThread; connect(t, &MyThread::sendNum, this, [=](int num) {ui.label->setText(QString::number(num)); }); connect(ui.pushButton, &QPushButton::clicked, this, [=]() { t->start(); }); }
标签:Qt,parent,int,子类,MyThread,num,线程,QThread From: https://www.cnblogs.com/shiyixirui/p/17439082.html