QT 工厂配置工具

简单用到了以下

  • 串口收发
  • 读写 excel
  • QT 表格控件
  • 登录页面跳转
  • QT 定时器
  • QT 动画
  • 鼠标滚轴事件

配置界面

image-20230802114945921

调试界面

image-20230802115008068

# 初始化

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "adminlogin.h"
#include "Conversion/conversion.h"

CMDPARSING_UNION cmdprotocolparsing;

extern bool liftlampCycleSendEnable;
extern int liftlampCycleSendnumber;

MainWindow* MainWindow::myMainWindow = nullptr;

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

    bmainUIinit(false);//UI初始化
    bmainServerPortinit();//串口初始化
    vmainflechazo_Time_Init();//定时器初始化
    vreadInfoLineEditInit();//map表初始化
    vcmdmapInit_liftlamp();//map指令初始化->超级牛B
    vanimationInit();//动画初始化

    BtnConfigStatus = false;

    //1、注册安装事件过滤
    ui->label_test_lamp_up_img_2->installEventFilter(this);
    ui->label_test_lamp_down_img_2->installEventFilter(this);
    ui->lineEdit_liftlampID->installEventFilter(this);

    isSaveExcel=false;
}

# 串口收发

bool MainWindow::bmainServerPortinit(void)
{
    serialPort = new QSerialPort;

    return true;
}

//搜索可用的串口,并添加到串口组合框
void MainWindow::vmainSearch_SerialPorts(void)
{
    if(ui->comboBox_com->count()==0){
        ui->comboBox_com->clear();

        foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
        {
            ui->comboBox_com->addItem(info.portName());//+info.description());
        }
    }
}

//从串口接收数据,存入接收区不处理,超时后再处理
void MainWindow::ReadSerialData()
{
    flechazoTime_ms = 0;
    receiveflag=true;
    rxDatas+=serialPort->readAll();
}

//串口接收
void MainWindow::vmainCom_recieve_data()
{
    flechazoTime_ms++;
    if((receiveflag)&&(flechazoTime_ms>=2))
    {
        receiveflag=false;
        if(ui->checkBox_select_show_hex->isChecked())    //十六进制显示
        {
             context = rxDatas.toHex();//转十六进制
             context = context.toUpper();//转大写

             QByteArray buffer,tmp, src;
             buffer = QByteArray::fromHex(context.toLatin1());
             for(int i=0;i<rxDatas.size();i++){
                cmdprotocolparsing.byte[i] = buffer[i];
             }
             //解析
             vprotocol_liftlamp_cmdparsing(rxDatas.size());

             //添加空格
             src = context.toLatin1();
             for (int i = 0; i < src.size(); i++ )
             {
                 tmp.append(src.at(i));
                 if (i % 2) tmp.append(0x20);
             }
             context = tmp;

        }
        else    //ASCII显示
        {
            context = QString::fromLocal8Bit(rxDatas);
        }
        //添加接收显示头
        QString timeStrLine="["+QDateTime::currentDateTime().toString("hh:mm:ss")+"][接收]:🐬 ";
        context = timeStrLine+context;//+"\n\r";

        QString content = "<span style=\" color:blue;\">"+context+"</span>";
        ui->textBrowser->append(content);

        rxDatas.clear();
    }
}

//打开串口
void MainWindow::on_pushButton_com_clicked()
{
    if(ui->pushButton_com->text()=="打开串口"){
        //获取COM口
        serialPort->setPortName(ui->comboBox_com->currentText());
        //打开串口
        if(serialPort->open(QIODevice::ReadWrite))
        {
            //设置波特率
            serialPort->setBaudRate(115200);
            //设置数据位数
            serialPort->setDataBits(QSerialPort::Data8);
            //设置奇偶校验
            serialPort->setParity(QSerialPort::NoParity);
            //设置流控制
            serialPort->setFlowControl(QSerialPort::NoFlowControl);

            //连接槽函数
            connect(serialPort, &QSerialPort::readyRead, this, &MainWindow::ReadSerialData);
            // 设置控件可否使用

            ui->pushButton_com->setText("关闭串口");
        }else{
            //打开串口失败
            QMessageBox::information(this,tr("发生错误啦"),tr("打开串口失败!"),QMessageBox::Ok);

        }
    }else if(ui->pushButton_com->text()=="关闭串口"){
        serialPort->clear();
        serialPort->close();
        ui->pushButton_com->setText("打开串口");
    }
}

void MainWindow::ServerPortSendData(QString qstring_context){
    //处理成16进制
    QByteArray flechazoSend_buffer;
    QString flechazoSend_msg="";
    if ( qstring_context.indexOf(" ") > 0)
    {
        bool ok;
        char data;
        QStringList list;
        list = qstring_context.split(" ");
        for (int i = 0; i < list.count(); i++)
        {
            if (list.at(i) == " ")
                continue;
            if (list.at(i).isEmpty())
                continue;
            data = (char)list.at(i).toInt(&ok, 16);
            if (!ok)
            {
                QMessageBox::information(this, tr("提示消息"), tr("输入的数据格式有错误!"), QMessageBox::Ok);

                return;
            }
            flechazoSend_buffer.append(data);
        }
         flechazoSend_msg = qstring_context.toUpper();
    }
    else
    {
        QByteArray tmp, src,myqsarraydata;
        myqsarraydata=qstring_context.toLatin1();
        flechazoSend_buffer = QByteArray::fromHex(myqsarraydata);
        src = qstring_context.toLatin1();
        for (int i = 0; i < src.size(); i++ )
        {
            tmp.append(src.at(i));
            if (i % 2) tmp.append(0x20);
        }
        flechazoSend_msg = tmp;
    }

    //发送数据
    if (serialPort && serialPort->isOpen())
    {
        while(!serialPort->isWritable());
        qDebug()<<"**************************buf : "<<flechazoSend_buffer.toHex();
        QString timeStrLine="["+QDateTime::currentDateTime().toString("hh:mm:ss")+"][发送]:🚀 ";
        QString content = "<span style=\" color:red;\">"+timeStrLine +flechazoSend_msg+"\n\r</span>";
        ui->textBrowser->append(content);

        serialPort->write(flechazoSend_buffer);

        //界面控制
        ui->textBrowser->setTextColor(Qt::red);
    }
    else
    {
        ui->textBrowser->append("串口并没有打开!");
        //QMessageBox::question(this, tr("提示"),QString(tr("串口并没有打开!")),QMessageBox::Ok, QMessageBox::Cancel);
    }
}

# QT 定时器

bool MainWindow::vmainflechazo_Time_Init(void)
{
    flechazoTimer_s = new QTimer;//用于1s1次的定时任务
    flechazoTimer = new QTimer;//用于串口超时接收

    flechazoTimer_s->start(1000);
    flechazoTimer->start(20);

    connect(flechazoTimer, &QTimer::timeout,this,&MainWindow::vmainCom_recieve_data);
    connect(flechazoTimer_s, &QTimer::timeout,this,&MainWindow::vmainflechazo_s);

    InquiryLampCurrentTimer = new QTimer;//用于1s1次的定时任务
    connect(InquiryLampCurrentTimer, &QTimer::timeout,this,&MainWindow::vTime_inquiry_lamp_current_handle);

    liftlampUporDown_t = new QTimer;//上下闪烁
    connect(liftlampUporDown_t, &QTimer::timeout,this,&MainWindow::vanimLampUporDown);

    return true;
}


//定时器中断->1s进入1次
bool MainWindow::vmainflechazo_s(void)
{
    if(!serverportstatus){
        //如果串口未连接则搜索串口
        vmainSearch_SerialPorts();
        //定时发送
        vprotocol_liftlamp_send_Auto();
    }

    return true;
}

# 鼠标事件

//2、重写eventFilter方法,点击lineEdit控件的事件
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    //鼠标点击时间
    if(event->type() == QEvent::MouseButtonRelease){
        if(qobject_cast<QLabel*>(obj) == ui->label_test_lamp_up_img_2)
        {
            vcmdmap_Cycle_Send_Over_ID(true);
            return true;
        }else if(qobject_cast<QLabel*>(obj) == ui->label_test_lamp_down_img_2){
            vcmdmap_Cycle_Send_Over_ID(false);
            return true;
        }
    }
    if(event->type() == QEvent::MouseButtonRelease){

    }

    return false;
}

//----------------------鼠标滚轴----------------------//
void MainWindow::wheelEvent(QWheelEvent *event)
{
    //如果焦点是ID就可以滚轴触发增减
    QLineEdit* lineEditFocus =
            qobject_cast<QLineEdit*>(ui->tabWidget_factory->focusWidget());
    if(lineEditFocus==ui->lineEdit_liftlampID){
        // 当滚轮远离使用者时进行放大,当滚轮向使用者方向旋转时进行缩小
        if(event->delta() > 0){
            vcmdmap_Cycle_Send_Over_ID(true);
        }else{
            vcmdmap_Cycle_Send_Over_ID(false);
        }
    }
}

# 全选

void MainWindow::on_pushButton_selectall_clicked()
{
    bool status;
    //全选
    if(ui->pushButton_selectall->text()=="全选"){
        status=true;
        ui->pushButton_selectall->setText("清空选择");
    }else if(ui->pushButton_selectall->text()=="清空选择"){
        status=false;
        ui->pushButton_selectall->setText("全选");
    }

    QObjectList checkboxList = ui->tab_produce->children();

    for (int i=0;i<checkboxList.count();i++) {
        QObject  *currentobject=checkboxList[i];
        if(QString(currentobject->metaObject()->className())==QString("QCheckBox"))
        {
            QCheckBox *currentcheckbox = (QCheckBox *)currentobject;
            currentcheckbox->setChecked(status);
        }
     }
}

# 登录界面跳转

//管理员登录
void MainWindow::on_pushButton_admin_login_clicked()
{
    if(ui->pushButton_admin_login->text()=="管理登录"){
        ui->pushButton_admin_login->setText("退出");
        MainWindow::hide();
        //跳入登录界面
        static adminlogin UI_LOGIN;
        UI_LOGIN.show();
    }else if(ui->pushButton_admin_login->text()=="退出"){
        //上锁,初始化UI
        bmainUIinit(false);
        ui->pushButton_admin_login->setText("管理登录");
    }
}

# 动画

//动画初始化
void MainWindow::vanimationInit(){

    animation_down = new QPropertyAnimation;
    animation_down->setTargetObject(ui->pushButton_into_debug_anim_lamp);
    animation_down->setPropertyName("pos");
    animation_down->setDuration(2000);
    //拿到坐标
    QPoint down_pos = ui->pushButton_into_debug_anim_lamp->pos();
    animation_down->setStartValue(down_pos);
    down_pos.setY(down_pos.y()+45);
    animation_down->setEndValue(down_pos);


    animation_up = new QPropertyAnimation;
    animation_up->setTargetObject(ui->pushButton_into_debug_anim_lamp);
    animation_up->setPropertyName("pos");
    animation_up->setDuration(2000);
    //拿到坐标
    animation_up->setStartValue(down_pos);
    down_pos.setY(down_pos.y()-45);
    animation_up->setEndValue(down_pos);


}

void MainWindow::vanimationLampOpen(bool status){
    if(status){//开灯
        //static QColor color = QColorDialog::getColor(Qt::black, this, "请选择颜色");
        int r = 225, g = 225, b = 225;
        //color.getRgb(&r,&g,&b);
        ui->pushButton_into_debug_anim_lamp->setStyleSheet(QString("background-color: rgb(%1,%2,%3)").arg(r).arg(g).arg(b));
    }else{//关灯
        //static QColor color = QColorDialog::getColor(Qt::black, this, "请选择颜色");
        int r = 160, g = 32, b = 240;
        //color.getRgb(&r,&g,&b);
        ui->pushButton_into_debug_anim_lamp->setStyleSheet(QString("background-color: rgb(%1,%2,%3)").arg(r).arg(g).arg(b));
    }
}


//动画,上升下降
void MainWindow::vanimLampLift(bool status){
    //标记上升或下降
    bLampUporDown_flag = status;
    vanimLampUporDown_number=0;
    //开启定时器
    liftlampUporDown_t->start(100);

}


//上下闪烁,定时器
void MainWindow::vanimLampUporDown(){
    if(++vanimLampUporDown_number<100){
        if(vanimLampUporDown_number%2){
            //显示控件
            if(bLampUporDown_flag){
                //上升
                ui->label_test_lamp_up_img->show();
                ui->label_test_lamp_down_img->hide();
            }else{
                //下降
                ui->label_test_lamp_down_img->show();
                ui->label_test_lamp_up_img->hide();
            }
        }else{
            //隐藏控件
            if(bLampUporDown_flag){
                //上升
                ui->label_test_lamp_up_img->hide();
            }else{
                //下降
                ui->label_test_lamp_down_img->hide();
            }
        }

    }else{
        ui->label_test_lamp_up_img->hide();
        ui->label_test_lamp_down_img->hide();
        vanimLampUporDown_number=0;
        liftlampUporDown_t->stop();
    }
}

# 指令处理

void MainWindow::vprotocol_liftlamp_send(QString value){
    //拼接字符串
    QString qstring_context = "";
    //帧头
    qstring_context.append("FB");
    //添加指令
    qstring_context.append(value);
    //添加状态
    qstring_context.append("00");
    //添加源设备
    qstring_context.append("00000000");
    //添加目标设备
    if(ui->tabWidget_factory->currentIndex()==0){
        qstring_context.append("00000000");
    }else{
        if(value=="040102"){
            qstring_context.append("00000000");
        }else{
            qstring_context.append(str_uint8_t_to_str(ucprotocollampSmallModeConvert(qstring_to_uint8(ui->lineEdit_liftlamp_ID->text()),4),4));
        }
    }

    //添加参数
    QString (MainWindow::*getpar)(void);
    getpar=cmdmap_liftlamp.value(cmdmap_liftlamp_parsing.value(value));
    qstring_context.append((this->*getpar)());

    //计算CRC
    QString str_crc=qstring_context;
    str_crc.remove(0,2);//去掉帧头
    qstring_context.append(qstrCrcCalc(str_crc).mid(2,2)+qstrCrcCalc(str_crc).mid(0,2));
    //qstring_context.append(qstrCrcCalc(str_crc));

    //添加帧尾
    qstring_context.append("FE");
    //发送
    ServerPortSendData(qstring_context);
}

具体的 demo

https://gitee.com/flechazo5201314/qtfactory
更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

flechazo 微信支付

微信支付

flechazo 支付宝

支付宝

flechazo 贝宝

贝宝