Qt的多线程(非重写run函数和继承Movetothread)

首先设计一个qt界面,包含4个button按钮,2个lineEdit,如图所示
在这里插入图片描述
界面测试多线程功能如下:
Pushbutton1和stop1按钮控制线程1的开始和结束,线程中使用while true死循环,输出从0开始,间隔10ms加1;Pushbutton2和stop2按钮控制线程2的开始和结束,线程中使用while true死循环,输出从0开始,间隔100ms加1。
mainwindow.h文件如下:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QThread>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    int i = 0;
    void f1();
    int f1_end_flag = 0;

    void f2();
    int j = 0;
    int f2_end_flag = 0;

private slots:
    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

    void on_pushButton_stop1_clicked();

    void on_pushButton_stop2_clicked();

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

f1_end_flag和f2_end_flag是线程1和线程2停止标志。
mainwindow.cpp文件如下:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Windows.h"
#include <QString>
#include <QtConcurrent/QtConcurrent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

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

void MainWindow::f1()
{
    f1_end_flag = 0;
    while (1) {
        i++;
        Sleep(10);
        ui->lineEdit->setText(QString::number(i));
        if (f1_end_flag == 1)
        {
            break;
        }
    }
}

void MainWindow::f2()
{
    f2_end_flag = 0;
    while (1) {
        j++;
        Sleep(100);
        ui->lineEdit_2->setText(QString::number(j));
        if(f2_end_flag == 1)
        {
            break;
        }
    }
}


void MainWindow::on_pushButton_clicked()
{
    QtConcurrent::run(this,&MainWindow::f1);
}


void MainWindow::on_pushButton_2_clicked()
{
    QtConcurrent::run(this,&MainWindow::f2);
}


void MainWindow::on_pushButton_stop1_clicked()
{
    f1_end_flag = 1;
}


void MainWindow::on_pushButton_stop2_clicked()
{
    f2_end_flag = 1;
}


运行结果如下:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值