从零开始实现自己的串口调试助手(8)-循环发送

循环发送

准备

创建槽函数

设置QSpinBox的最大值

注意:

// 我们不能在qt的ui线程中延时 ,否则将导致页面刷新问题

//QThread::msleep(ui->spinBox->text().toInt());//设置下次发送时间间隔

定时器实现

关联信号与槽:

//添加自动换行定时器

btnConTimer = new QTimer(this);

connect(btnConTimer,&QTimer::timeout,this,&Widget::btnHandler);

创建控件处理函数

cpp 复制代码
void Widget::btnHandler()
{
    if(btnIndex<buttons.size()) { // 遍历我们创建的多文本控件数组
        QPushButton *btnTmp = buttons[btnIndex];// 读到每一个发送按钮
        emit btnTmp->clicked(); //发出被点击信号 -->跳到对应处理函数-->发送
        btnIndex++;
    }
    else {
        btnIndex  = 0; // 复位
    }

}

实现定时器控制槽函数

cpp 复制代码
void Widget::on_checkBox_send_clicked(bool checked)
{
    if(checked){ // 循环发送被勾选
        ui->spinBox->setEnabled(false);
        btnConTimer->start(ui->spinBox->text().toInt()); // 根据框内的值设置定时器周期
    }
    else{
        ui->spinBox->setEnabled(true);
        btnConTimer->stop();
    }
}

线程实现:

自定义线程类

customthread.h
cpp 复制代码
#ifndef CUSTOMTHREAD_H
#define CUSTOMTHREAD_H

#include <QThread>
#include <QWidget>
#include "widget.h"

class customThread : public QThread
{
    Q_OBJECT // 需要用这个宏里面的信号与槽
public:
    customThread(QWidget *parent);

protected:
   void run() override;

signals:
 void  threadTimeout();


};

#endif // CUSTOMTHREAD_H
customthread.cpp
cpp 复制代码
#include "customthread.h"



customThread::customThread(QWidget *parent):QThread(parent)
{

}

void customThread::run()
{
    while (true) {
    msleep(1000);
    emit threadTimeout();//每隔一秒发一次超时信号
    }

}

线程的信号处理

// 自动换行线程初始化

myThread = new customThread(this);

connect(myThread,&customThread::threadTimeout,this,&Widget::btnHandler);

修改槽函数

cpp 复制代码
void Widget::on_checkBox_send_clicked(bool checked)
{
    if(checked){ // 循环发送被勾选
        ui->spinBox->setEnabled(false);
        myThread->start(); //线程开始
        //btnConTimer->start(ui->spinBox->text().toInt()); // 根据框内的值设置定时器周期
    }
    else{
        ui->spinBox->setEnabled(true);
        myThread->terminate();
        //btnConTimer->stop();
    }
}

实现效果

相关推荐
mit6.82442 分钟前
并查集|栈
c++
Android小码家43 分钟前
Vscode + docker + qt 网络监听小工具
vscode·qt·docker
中国胖子风清扬1 小时前
Rust 序列化技术全解析:从基础到实战
开发语言·c++·spring boot·vscode·后端·中间件·rust
yudiandian20141 小时前
【QT 5.12.12 打包-Windows 平台下】
开发语言·qt
岁忧2 小时前
(LeetCode 面试经典 150 题) 200. 岛屿数量(深度优先搜索dfs || 广度优先搜索bfs)
java·c++·leetcode·面试·go·深度优先
一枝小雨2 小时前
【OJ】C++ vector类OJ题
数据结构·c++·算法·leetcode·oj题
一枝小雨2 小时前
【C++】Vector完全指南:动态数组高效使用
开发语言·c++·笔记·vector·学习笔记·std库
buyutang_2 小时前
C/C++ Linux系统编程:线程控制详解,从线程创建到线程终止
linux·c语言·c++·学习
Qiang_san3 小时前
GNU Make | C/C++项目自动构建入门
c语言·c++·gnu
源代码•宸3 小时前
Leetcode—2749. 得到整数零需要执行的最少操作数【中等】(__builtin_popcountl)
c++·经验分享·算法·leetcode·位运算