admin 管理员组

文章数量: 887021

project

文章目录

  • 效果![在这里插入图片描述](.png)
  • 源码
    • widget.cpp
    • widget.h

效果

源码

widget.cpp

#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);Init();tableWidgetInit();listWidgetInit();
}Widget::~Widget()
{delete ui;
}void Widget::Init(void){resize(1130,660);setWindowTitle("serial_port");SendByte=0;ReceByte=0;serial = new QSerialPort(this);connect(serial,SIGNAL(readyRead()),this,SLOT(serialPort_readyRead()));connect(ui->btn_serial_scan,SIGNAL(clicked(bool)),this,SLOT(btn_serial_scan_clicked()));connect(ui->btn_serial_send,SIGNAL(clicked(bool)),this,SLOT(btn_serial_send_clicked()));connect(ui->btn_serial_open,SIGNAL(clicked(bool)),this,SLOT(btn_serial_open_clicked()));connect(ui->btn_tx_clear,SIGNAL(clicked(bool)),this,SLOT(btn_tx_clear_clicked()));connect(ui->btn_rx_clear,SIGNAL(clicked(bool)),this,SLOT(btn_rx_clear_clicked()));connect(ui->btn_file_save,SIGNAL(clicked(bool)),this,SLOT(btn_file_save_clicked()));connect(ui->btn_file_open,SIGNAL(clicked(bool)),this,SLOT(btn_file_open_clicked()));connect(ui->btn_counter_clear,SIGNAL(clicked(bool)),this,SLOT(btn_clear_counter_clicked()));connect(ui->chk_rx_tx,SIGNAL(clicked(bool)),this,SLOT(chk_rx_tx_clicked()));connect(ui->chk_rx_hex,SIGNAL(clicked(bool)),this,SLOT(chk_rx_hex_clicked()));connect(ui->chk_tx_tx,SIGNAL(clicked(bool)),this,SLOT(chk_tx_tx_clicked()));connect(ui->chk_tx_hex,SIGNAL(clicked(bool)),this,SLOT(chk_tx_hex_clicked()));connect(ui->chk_rx_pause,SIGNAL(clicked(bool)),this,SLOT(chk_rx_pause_clicked()));connect(ui->lineEdit,SIGNAL(returnPressed()),this,SLOT(on_lineEdit_ending()));portTime=0;Times = 0;lineEditData = 1000;timer = new QTimer;timer->start(1);connect(timer,SIGNAL(timeout()),this,SLOT(timerout_event()));ui->cmb_baud->setCurrentIndex(5);ui->cmb_databit->setCurrentIndex(3);ui->cmb_crcbit->setCurrentIndex(2);ui->cmb_stopbit->setCurrentIndex(0);ui->lineEdit->setText("1000");ui->chk_tx_tx->setCheckState(Qt::Checked);//勾选ui->chk_rx_tx->setCheckState(Qt::Checked);//勾选ui->btn_serial_send->setEnabled(false);//按钮是灰色的,不响应任何触发事件ui->chk_timer->setEnabled(false);//按钮是灰色的,不响应任何触发事件
}//打开串口
void Widget::btn_serial_open_clicked()
{qDebug()<<"open serialport"<<endl;if(ui->btn_serial_open->text()==QString("打开串口")){//设置串口名serial->setPortName(ui->cmb_serail->currentText());qDebug()<<ui->cmb_serail->currentText()<<endl;//设置波特率serial->setBaudRate(ui->cmb_baud->currentText().toInt());qDebug()<<ui->cmb_baud->currentText().toInt()<<endl;//设置数据位switch(ui->cmb_databit->currentText().toInt()){case 5:serial->setDataBits(QSerialPort::Data5);break;case 6:serial->setDataBits(QSerialPort::Data6);break;case 7:serial->setDataBits(QSerialPort::Data7);break;case 8:serial->setDataBits(QSerialPort::Data8);break;default:serial->setDataBits(QSerialPort::UnknownDataBits);break;}//设置奇偶校验位switch(ui->cmb_crcbit->currentIndex()){case 0:serial->setParity(QSerialPort::EvenParity);break;case 1:serial->setParity(QSerialPort::MarkParity);break;case 2:serial->setParity(QSerialPort::NoParity);break;case 3:serial->setParity(QSerialPort::OddParity);break;default:serial->setParity(QSerialPort::UnknownParity);break;}//设置停止位switch (ui->cmb_stopbit->currentIndex()){case 0:serial->setStopBits(QSerialPort::OneStop);break;case 1:serial->setStopBits(QSerialPort::OneAndHalfStop);break;case 2:serial->setStopBits(QSerialPort::TwoStop);break;default:serial->setStopBits(QSerialPort::UnknownStopBits);break;}//设置流控制serial->setFlowControl(QSerialPort::NoFlowControl);//打开串口if(!serial->open(QIODevice::ReadWrite)){QMessageBox::about(NULL,"提示","无法打开串口");return;}//下拉控件失能ui->cmb_serail->setEnabled(false);ui->cmb_baud->setEnabled(false);ui->cmb_databit->setEnabled(false);ui->cmb_crcbit->setEnabled(false);ui->cmb_stopbit->setEnabled(false);ui->btn_serial_scan->setEnabled(false);ui->chk_timer->setEnabled(true);ui->btn_serial_open->setText(tr("关闭串口"));ui->btn_serial_send->setEnabled(true);}else{//关闭串口serial->close();//下拉按键使能ui->cmb_serail->setEnabled(true);ui->cmb_baud->setEnabled(true);ui->cmb_databit->setEnabled(true);ui->cmb_crcbit->setEnabled(true);ui->cmb_stopbit->setEnabled(true);ui->btn_serial_scan->setEnabled(true);ui->chk_timer->setEnabled(false);ui->btn_serial_open->setText(tr("打开串口"));//发送失能ui->btn_serial_send->setEnabled(false);}
}//串口扫描
void Widget::btn_serial_scan_clicked(){int i,n;qDebug()<<"btn_serial_scan_clicked"<<endl;ui->cmb_serail->clear();portStringLine.clear();foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())portStringLine +=info.portName();n=portStringLine.size();for(i=0;i<n;i++){serial->setPortName(portStringLine[i]);if(!serial->open(QIODevice::ReadWrite)){portStringLine[i]+="(不可用)";QVariant v(0);          //禁用ui->cmb_serail->setItemData(1, v, Qt::UserRole - 1);}else{QVariant v(1|32);       //可用ui->cmb_serail->setItemData(1, v, Qt::UserRole - 1);}serial->close();}ui->cmb_serail->addItems(portStringLine);
}//串口接收
void Widget::serialPort_readyRead()
{int i,length;QString lasttext;if(ui->chk_rx_pause->checkState()!=Qt::Checked){lasttext=ui->tx_rev->toPlainText();Receivetext = serial->readAll();ReceByte+=Receivetext.length();ui->label_rx->setText(QString::number(ReceByte));if(ui->chk_rx_pause->checkState()==Qt::Checked){Receivetext=Receivetext.toLatin1().toHex();     //字符串转十六进制length=Receivetext.length();for(i=0;i<=length/2;i++){Receivetext.insert((2+3*i),' ');            //插入空格字符串}}elseReceivetext=Receivetext.toLatin1();lasttext=lasttext.append(Receivetext);ui->tx_rev->setText(lasttext);}
}//定时事件,1ms
void Widget::timerout_event(){int t=500;                                                  //扫描串口时间Times++;portTime++;if(Times>=lineEditData)                                     //定时发送{if(ui->chk_timer->checkState()==Qt::Checked)Widget::btn_serial_send_clicked();Times=0;}if(portTime==t)                                             //定时扫描串口{QStringList newPortStringList;newPortStringList.clear();foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())newPortStringList += info.portName();if(newPortStringList.size() != portStringLine.size()){portStringLine = newPortStringList;ui->cmb_serail->clear();ui->cmb_serail->addItems(portStringLine);}portTime=0;}
}//串口发送
void Widget::btn_serial_send_clicked()
{QByteArray bytearray;Sendtext=ui->tx_send->toPlainText();if(ui->chk_tx_wrap->checkState()==Qt::Checked)Sendtext += '\n';if(ui->chk_tx_hex->checkState()!=Qt::Checked)bytearray = Sendtext.toLatin1();elsebytearray = QByteArray::fromHex(Sendtext.toUtf8());     //十六进制转字符串serial->write(bytearray);//定长发送//serial->write((const char *)param_data,16);SendByte+=Sendtext.length();ui->label_tx->setText(QString::number(SendByte));ui->tx_send->moveCursor(QTextCursor::End);
}//清空计数
void Widget::btn_clear_counter_clicked(){qDebug()<<"btn_clear_counter_clicked"<<endl;SendByte = 0;ReceByte = 0;ui->label_tx->setText(QString::number(SendByte));ui->label_rx->setText(QString::number(ReceByte));
}//清空接收区
void Widget::btn_rx_clear_clicked(){qDebug()<<"btn_rx_clear_clicked"<<endl;ui->tx_rev->clear();
}//清空发送区
void Widget::btn_tx_clear_clicked(){qDebug()<<"btn_tx_clear_clicked"<<endl;ui->tx_send->clear();
}//文本进制接收
void Widget::chk_rx_tx_clicked(){ui->chk_rx_tx->setCheckState(Qt::Checked);ui->chk_rx_hex->setCheckState(Qt::Unchecked);ui->chk_rx_pause->setCheckState(Qt::Unchecked);
}//hex进制接收
void Widget::chk_rx_hex_clicked(){ui->chk_rx_tx->setCheckState(Qt::Unchecked);ui->chk_rx_hex->setCheckState(Qt::Checked);ui->chk_rx_pause->setCheckState(Qt::Unchecked);
}//暂停接收
void Widget::chk_rx_pause_clicked()
{qDebug()<<"chk_rx_pause_clicked"<<endl;ui->chk_rx_tx->setCheckState(Qt::Unchecked);ui->chk_rx_hex->setCheckState(Qt::Unchecked);ui->chk_rx_pause->setCheckState(Qt::Checked);
}//文本形式发送
void Widget::chk_tx_tx_clicked(){ui->chk_tx_tx->setCheckState(Qt::Checked);ui->chk_tx_hex->setCheckState(Qt::Unchecked);
}//hex进制发送
void Widget::chk_tx_hex_clicked(){ui->chk_tx_tx->setCheckState(Qt::Unchecked);ui->chk_tx_hex->setCheckState(Qt::Checked);
}//打开文件
void Widget::btn_file_open_clicked(){QString fileName = QFileDialog::getOpenFileName(this);QFile file(fileName); //新建QFile对象if(!file.open((QFile::ReadOnly|QFile::Text))){QMessageBox::warning(this,tr("多文档编辑器"),tr("无法读取文件 %1:\n%2").arg(fileName,file.errorString()));}QTextStream in(&file);//新建文本流对象// 鼠标指针变为等待状态QApplication::setOverrideCursor(Qt::WaitCursor);//读取文件的全部文本内容,并添加到编辑器中ui->tx_send->setPlainText(in.readAll());//鼠标指针恢复为原来状态QApplication::restoreOverrideCursor();ui->tx_rev->setVisible(true);
}//保存文件
void Widget::btn_file_save_clicked(){QString fileName = QFileDialog::getSaveFileName(this);QFile file(fileName);if (!file.open(QFile::WriteOnly | QFile::Text)){// %1和%2分别对应后面arg两个参数,/n起换行的作用QMessageBox::warning(this, tr("多文档编辑器"),tr("无法写入文件 %1:/n %2").arg(fileName, file.errorString()));}QTextStream out(&file);// 鼠标指针变为等待状态QApplication::setOverrideCursor(Qt::WaitCursor);out << ui->tx_rev->toPlainText();// 鼠标指针恢复原来的状态QApplication::restoreOverrideCursor();
}//输入定时时间
void Widget::on_lineEdit_ending()
{if(ui->lineEdit->text().toInt()>0)lineEditData=ui->lineEdit->text().toInt();qDebug()<<ui->lineEdit->text()<<endl;
}//窗体大小事件
void Widget::resizeEvent(QResizeEvent *event){qDebug()<<"old:"<<event->oldSize()<<endl;qDebug()<<"new:"<<event->size()<<endl;
}//tablewidget 初始化
void Widget::tableWidgetInit(){int i,j;ui->tableWidget->horizontalHeader()->setStretchLastSection(true);//设置每一行最后一个单元格不留空格ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);//设置自适应大小ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//设置等宽//设置表格中每一行的内容row_count = ui->tableWidget->rowCount();column_count = ui->tableWidget->columnCount();qDebug()<<"row"<<row_count<<"column"<<column_count;for( i=0;i<row_count;i++){for( j=0;j<column_count;j++){ui->tableWidget->setItem(i,j,new QTableWidgetItem(QString::number(j)));}}//打印表格数据//遍历数据QTableWidgetItem* item;QString str;for(int i = 0; i < ui->tableWidget->rowCount(); i++){for(int j = 0; j < ui->tableWidget->columnCount(); j++){item = ui->tableWidget->item(i, j);str = str + item->text() + " ";}}qDebug()<<"str = "<<str;// 返回鼠标单击的所在单元格的row和colconnect(ui->tableWidget,SIGNAL(cellClicked(int,int)),this,SLOT(show_prodcut_sets(int,int)));connect(ui->tableWidget->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),SLOT(doProcessSelLine(void)));
}//单击某个单元格
void Widget::show_prodcut_sets(int row,int col)
{QString str;qDebug() << "所点击的单元格的row=" << row << ",col=" << col;// 获取所点击的单元格QTableWidgetItem* item = ui->tableWidget->item(row ,col);qDebug() <<"内容为:"<< item->text();
}//选中某一列
void Widget::doProcessSelLine(){int current_column;QString str;QTableWidgetItem* item;current_column = ui->tableWidget->currentColumn();//获取当前行号//打印行内容for(int j = 0; j < ui->tableWidget->columnCount(); j++){item = ui->tableWidget->item(current_column, j);str = str + item->text() + " ";}qDebug()<<str<<endl;
}void Widget::listWidgetInit(){mylistWidget = ui->listWidget;// 点击列表时,当前选中的项connect(ui->listWidget,&QListWidget::itemClicked,this,  &Widget::SLOT_ListWidget_ItemClicked);
}void Widget::SLOT_ListWidget_ItemClicked(QListWidgetItem* item)
{qDebug() << item->text();QString text;text = item->text();if((text)=="连接"){qDebug()<<111111<<endl;}
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QtSerialPort>
#include <QtSerialPortVersion>
#include <QMessageBox>
#include <QDebug>
#include <QFile>
#include <QFileDialog>
#include <QTimer>
#include <QStringList>
#include <QMouseEvent>
#include <QListWidget>
namespace Ui {
class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = nullptr);~Widget();int Times,portTime,lineEditData;
private:Ui::Widget *ui;
private:void Init(void);QSerialPort *serial;                    //串口端口QTimer *timer;                          //定时器QString Sendtext,Receivetext;           //发送、接收缓存区long int SendByte,ReceByte;             //发送、接收字符数QStringList portStringLine;             //端口链表int row_count,column_count;QListWidget *mylistWidget;void tableWidgetInit(void);void listWidgetInit(void);private slots:void serialPort_readyRead();            //串口接收void timerout_event();                  //定时发送、更新串口void btn_serial_scan_clicked();         //扫描串口void btn_serial_send_clicked();         //串口发送void btn_serial_open_clicked();         //打开串口void btn_clear_counter_clicked();       //清空计数void btn_tx_clear_clicked();            //清空发送区void btn_rx_clear_clicked();            //清空接收区void btn_file_save_clicked();           //保存文件void btn_file_open_clicked();           //文件打开void chk_rx_tx_clicked();               //文本方式接收void chk_rx_hex_clicked();              //hex方式接收void chk_tx_tx_clicked();               //文本方式发送void chk_tx_hex_clicked();              //hex方式发送void chk_rx_pause_clicked();            //暂停接收void on_lineEdit_ending();              //输入定时时间void show_prodcut_sets(int,int);        //选择单元格void doProcessSelLine(void);            //选择行void SLOT_ListWidget_ItemClicked(QListWidgetItem *item);        //选中列表protected:void resizeEvent(QResizeEvent *event);
};#endif // WIDGET_H

本文标签: project