QThread的简单实用

8 篇文章 1 订阅

1.线程类workerthread.h

#ifndef WORKERTHREAD_H
#define WORKERTHREAD_H

#include <QThread>

class WorkerThread : public QThread
{
    Q_OBJECT
public:
    WorkerThread(QObject *parent = 0);
protected:
    void run();
signals:
    void done();
};

#endif // WORKERTHREAD_H

2.workerthread.cpp 用线程处理一个很耗时的循环,防止界面UI主线程卡顿

#include "workerthread.h"

WorkerThread::WorkerThread(QObject *parent):QThread(parent)
{

}

void WorkerThread::run()
{
    for(int i=0;i<1000000000; i++);
    emit done();
}

3.mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;

};
#endif // MAINWINDOW_H

4.3.mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QWidget"
#include "QVBoxLayout"
#include "QLCDNumber"
#include "QTimer"
#include "QPushButton"
#include "workerthread.h"
#include "work.h"
#include "QPointer"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QWidget *widget = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout;
    widget->setLayout(layout);
    QLCDNumber *lcd = new QLCDNumber(this);
    layout->addWidget(lcd);
    QPushButton *btn = new QPushButton(tr("start"),this);
    layout->addWidget(btn);
    setCentralWidget(widget);
    QTimer *timer = new QTimer(this);
    connect(timer , &QTimer::timeout,[=](){static int sec = 0; lcd->display(QString::number(sec++));});
    WorkerThread *wthread = new WorkerThread(this);
    connect(wthread,&WorkerThread::done,timer,&QTimer::stop);
    //connect(wthread,&WorkerThread::finished,wthread,&WorkerThread::deleteLater);
    connect(btn,&QPushButton::clicked,[=](){
        timer->start(10);
        wthread->start();});

}

MainWindow::~MainWindow()
{
    delete ui;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值