从零开始实现自己的串口调试助手(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();
    }
}

实现效果

相关推荐
lqjun08275 小时前
Qt程序单独运行报错问题
开发语言·qt
风中的微尘7 小时前
39.网络流入门
开发语言·网络·c++·算法
混分巨兽龙某某8 小时前
基于Qt Creator的Serial Port串口调试助手项目(代码开源)
c++·qt creator·串口助手·serial port
小冯记录编程8 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio
C_Liu_9 小时前
C++:类和对象(下)
开发语言·c++
coderxiaohan9 小时前
【C++】类和对象1
java·开发语言·c++
阿昭L9 小时前
MFC仿真
c++·mfc
老赵的博客11 小时前
c++ unqiue指针
java·jvm·c++
程序猿编码12 小时前
基于 Linux 内核模块的字符设备 FIFO 驱动设计与实现解析(C/C++代码实现)
linux·c语言·c++·内核模块·fifo·字符设备
怎么没有名字注册了啊12 小时前
MFC_Install_Create
c++·mfc