Qt串口通信开发之Qt串口通信模块QSerialPort开发完整实例(串口助手开发)
之前自己写了用于上位机做基本收发的界面,独立出来相当于一个串口助手,先贴图:
功能作为串口助手来说还算完善,五个发送槽,一个接收槽,可以检测可用串口并加上相关标志,串口设置,记数功能,还有菜单栏上的文件操作和一些选择功能。
下面说一说这个项目:
做这个串口助手分为两步,第一步是设计界面,第二部是功能的代码实现。
一、界面设计
界面设计用QtDesigner,当然用QtCreator的界面编辑器也可以,只不过感觉QtDesigner更好用一点,因为可以随时运行查看你的界面效果而不用编译整个项目输出一个可执行程序再看看界面效果,这样会影响效率。
界面设计你想界面是什么样就怎么样设计,拉控件,排版,设置大小,修改对象名等等,都在这上面做好,这些用程序写的话会很麻烦,工作量也大。这上面的对象名很重要,因为在后面的代码实现中会用到,这个界面用到的控件还是挺多的,这里也不一个一个讲,我直接贴出来:
senderGB_1-5都是一样的,改下数就行
当然,用你自己喜欢的命名也可以,后面程序改下名字就行。
二、代码实现
先贴代码
basictransceiver.h
#ifndefBASICTRANSCEIVER_H #defineBASICTRANSCEIVER_H #include#include"ui_basictransceiver.h" classQTimer; classSerialPortSetting; classQSerialPort; classQPushButton; classBasicTransceiver:publicQMainWindow,publicUi::BasicTransceiver { Q_OBJECT public: explicitBasicTransceiver(QWidget*parent=0); ~BasicTransceiver(); voidStringToHex(QStringstr,QByteArray&senddata); charConvertHexChar(charch); voidstartAutoSend(QPushButton*sendButton); voidsetConnections(); voidwriteHex(QTextEdit*textEdit); voidwriteChr(QTextEdit*textEdit); voidresetCnt(); protected: voiddragEnterEvent(QDragEnterEvent*event); voiddropEvent(QDropEvent*event); privateslots: voidcheckAutoSendCB(); voidon_cleanButton_clicked(); voidon_receiveTextBrowser_textChanged(); voidsetBaudRate(); voidsetParity(); voidsetDataBits(); voidsetStopBits(); voidsetFlowCtrl(); voidon_connectButton_toggled(boolchecked); voidsetComLabel(); voidsetBaudLabel(); voidwriteToBuf(); voidenabledSendButton(); voiddisabledSendButton(); voidenabledAutoSend(); voiddisabledAutoButton(); voidresetAutoSendCB(); voidreadMyCom(); voidcheckAvailablePorts(); voidon_checkAPButton_clicked(); voidcheckPort(); voidon_resetCntButton_clicked(); voidon_exitButton_clicked(); boolsaveAs(); voidopen(); //voidabout(); private: boolloadFile(constQString&fileName); boolreadFile(constQString&fileName); boolsaveFile(constQString&fileName); boolwriteFile(constQString&fileName); QTimer*Timer_AS;//自动发送定时器 QTimer*Timer_UPDATE; QTimer*Timer_CP;//定时检测串口是否存在 SerialPortSetting*SPSetting; QSerialPort*mySerialPort; QSet portSet; QVector iVec; QStringsenderFlag; QStringreadData; booltrashFlag=false; boolportIsOpen=false; intBaudCnt=0; intParityCnt=0; intDataBitsCnt=0; intStopBitsCnt=0; intFlowCtrlCnt=0; }; #endif//BASICTRANSCEIVER_H
basictransceiver.cpp
#include"basictransceiver.h" #include"serialportsetting.h" #include"ui_basictransceiver.h" #include"ui_serialportsetting.h" #include#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include BasicTransceiver::BasicTransceiver(QWidget*parent): QMainWindow(parent) { setupUi(this); setFixedSize(1074,627); receiveTextBrowser->setAcceptDrops(false);//缺省情况下,QTextEdit接受来自其他应用程序拖拽来的文本,把文件名显示出来。 senderTextEdit_1->setAcceptDrops(false); senderTextEdit_2->setAcceptDrops(false); senderTextEdit_3->setAcceptDrops(false); senderTextEdit_4->setAcceptDrops(false); senderTextEdit_5->setAcceptDrops(false); setAcceptDrops(true);//通过禁止QTextEdit控件的drop事件,允许主窗口得到drop事件 connectButton->setIcon(QIcon(":/images/open.png")); cleanButton->setIcon(QIcon(":/images/empty_bin.png")); checkAPButton->setIcon(QIcon(":/images/find.png")); resetCntButton->setIcon(QIcon(":/images/to_zero.png")); exitButton->setIcon(QIcon(":/images/exit.png")); actionWrite_data->setIcon(QIcon(":/images/write.png")); actionRead_data->setIcon(QIcon(":/images/read.png")); actionChoose_file->setIcon(QIcon(":/images/select_file.png")); exitAction->setIcon(QIcon(":/images/exit.png")); actionAbout->setIcon(QIcon(":/images/about.png")); sendButton_1->setIcon(QIcon(":/images/send.png")); sendButton_2->setIcon(QIcon(":/images/send.png")); sendButton_3->setIcon(QIcon(":/images/send.png")); sendButton_4->setIcon(QIcon(":/images/send.png")); sendButton_5->setIcon(QIcon(":/images/send.png")); setConnections(); emitcheckAvailablePorts(); Timer_CP=newQTimer(this); Timer_UPDATE=newQTimer(this); connect(Timer_UPDATE,SIGNAL(timeout()),this,SLOT(repaint())); Timer_UPDATE->start(2000); Timer_AS=newQTimer(this); } BasicTransceiver::~BasicTransceiver() { } voidBasicTransceiver::checkAutoSendCB() { QObject*signalSender=sender(); if(signalSender->objectName()=="autoSendCB_1") { if(autoSendCB_1->isChecked()) { intervalSB_1->setEnabled(false); autoSendCB_2->setEnabled(false); autoSendCB_3->setEnabled(false); autoSendCB_4->setEnabled(false); autoSendCB_5->setEnabled(false); startAutoSend(sendButton_1); }elseif(!autoSendCB_1->isChecked()){ Timer_AS->stop(); Timer_AS->disconnect(); intervalSB_1->setEnabled(true); autoSendCB_2->setEnabled(true); autoSendCB_3->setEnabled(true); autoSendCB_4->setEnabled(true); autoSendCB_5->setEnabled(true); enabledSendButton(); } }elseif(signalSender->objectName()=="autoSendCB_2"){ if(autoSendCB_2->isChecked()) { intervalSB_2->setEnabled(false); autoSendCB_1->setEnabled(false); autoSendCB_3->setEnabled(false); autoSendCB_4->setEnabled(false); autoSendCB_5->setEnabled(false); startAutoSend(sendButton_2); }elseif(!autoSendCB_2->isChecked()){ Timer_AS->stop(); Timer_AS->disconnect(); intervalSB_2->setEnabled(true); autoSendCB_1->setEnabled(true); autoSendCB_3->setEnabled(true); autoSendCB_4->setEnabled(true); autoSendCB_5->setEnabled(true); enabledSendButton(); } }elseif(signalSender->objectName()=="autoSendCB_3"){ if(autoSendCB_3->isChecked()) { intervalSB_3->setEnabled(false); autoSendCB_1->setEnabled(false); autoSendCB_2->setEnabled(false); autoSendCB_4->setEnabled(false); autoSendCB_5->setEnabled(false); startAutoSend(sendButton_3); }elseif(!autoSendCB_3->isChecked()){ Timer_AS->stop(); Timer_AS->disconnect(); intervalSB_3->setEnabled(true); autoSendCB_1->setEnabled(true); autoSendCB_2->setEnabled(true); autoSendCB_4->setEnabled(true); autoSendCB_5->setEnabled(true); enabledSendButton(); } }elseif(signalSender->objectName()=="autoSendCB_4"){ if(autoSendCB_4->isChecked()) { intervalSB_4->setEnabled(false); autoSendCB_1->setEnabled(false); autoSendCB_2->setEnabled(false); autoSendCB_3->setEnabled(false); autoSendCB_5->setEnabled(false); startAutoSend(sendButton_4); }elseif(!autoSendCB_4->isChecked()){ Timer_AS->stop(); Timer_AS->disconnect(); intervalSB_4->setEnabled(true); autoSendCB_1->setEnabled(true); autoSendCB_2->setEnabled(true); autoSendCB_3->setEnabled(true); autoSendCB_5->setEnabled(true); enabledSendButton(); } }elseif(signalSender->objectName()=="autoSendCB_5"){ if(autoSendCB_5->isChecked()) { intervalSB_5->setEnabled(false); autoSendCB_1->setEnabled(false); autoSendCB_2->setEnabled(false); autoSendCB_3->setEnabled(false); autoSendCB_4->setEnabled(false); startAutoSend(sendButton_5); }elseif(!autoSendCB_5->isChecked()){ Timer_AS->stop(); Timer_AS->disconnect(); intervalSB_5->setEnabled(true); autoSendCB_1->setEnabled(true); autoSendCB_2->setEnabled(true); autoSendCB_3->setEnabled(true); autoSendCB_4->setEnabled(true); enabledSendButton(); } } } //清除接收区的内容 voidBasicTransceiver::on_cleanButton_clicked() { if(trashFlag==true){ receiveTextBrowser->clear(); cleanButton->setIcon(QIcon(":/images/empty_bin.png")); } } voidBasicTransceiver::on_receiveTextBrowser_textChanged() { QStringtempStr=receiveTextBrowser->toPlainText(); if(!tempStr.isEmpty()){ trashFlag=true; if(autoClean->isChecked()){ if(tempStr.size()>6200){ receiveTextBrowser->clear(); cleanButton->setIcon(QIcon(":/images/empty_bin.png")); } }else{ cleanButton->setIcon(QIcon(":/images/clean.png")); } }else{ trashFlag=false; cleanButton->setIcon(QIcon(":/images/empty_bin.png")); } } voidBasicTransceiver::setBaudRate() { if(portIsOpen){ if(BAUDCB->currentText()=="115200") mySerialPort->setBaudRate(QSerialPort::Baud115200); elseif(BAUDCB->currentText()=="9600") mySerialPort->setBaudRate(QSerialPort::Baud9600); elseif(BAUDCB->currentText()=="1200") mySerialPort->setBaudRate(QSerialPort::Baud1200); elseif(BAUDCB->currentText()=="2400") mySerialPort->setBaudRate(QSerialPort::Baud2400); elseif(BAUDCB->currentText()=="4800") mySerialPort->setBaudRate(QSerialPort::Baud4800); elseif(BAUDCB->currentText()=="19200") mySerialPort->setBaudRate(QSerialPort::Baud19200); elseif(BAUDCB->currentText()=="38400") mySerialPort->setBaudRate(QSerialPort::Baud38400); elseif(BAUDCB->currentText()=="57600") mySerialPort->setBaudRate(QSerialPort::Baud57600); emitsetBaudLabel(); if(BaudCnt){ statusBar()->showMessage("BaudRatesetsuccessfully",2000); } ++BaudCnt; } } voidBasicTransceiver::setParity() { if(portIsOpen){ if(ParityCB->currentText()==QString::fromLocal8Bit("无校验")) mySerialPort->setParity(QSerialPort::NoParity); elseif(ParityCB->currentText()==QString::fromLocal8Bit("奇校验")) mySerialPort->setParity(QSerialPort::OddParity); elseif(ParityCB->currentText()==QString::fromLocal8Bit("偶校验")) mySerialPort->setParity(QSerialPort::EvenParity); if(ParityCnt){ statusBar()->showMessage("Paritysetsuccessfully",2000); } ++ParityCnt; } } voidBasicTransceiver::setDataBits() { if(portIsOpen){ if(DataBitsCB->currentText()=="8") mySerialPort->setDataBits(QSerialPort::Data8); elseif(DataBitsCB->currentText()=="7") mySerialPort->setDataBits(QSerialPort::Data7); elseif(DataBitsCB->currentText()=="6") mySerialPort->setDataBits(QSerialPort::Data6); elseif(DataBitsCB->currentText()=="5") mySerialPort->setDataBits(QSerialPort::Data5); if(DataBitsCnt){ statusBar()->showMessage("DataBitssetsuccessfully",2000); } ++DataBitsCnt; } } voidBasicTransceiver::setStopBits() { if(portIsOpen){ if(StopBitsCB->currentText()=="1") mySerialPort->setStopBits(QSerialPort::OneStop); elseif(StopBitsCB->currentText()=="1.5") mySerialPort->setStopBits(QSerialPort::OneAndHalfStop); elseif(StopBitsCB->currentText()=="2") mySerialPort->setStopBits(QSerialPort::TwoStop); if(StopBitsCnt){ statusBar()->showMessage("StopBitssetsuccessfully",2000); } ++StopBitsCnt; } } voidBasicTransceiver::setFlowCtrl() { if(portIsOpen){ if(FlowCtrlCB->currentText()=="off") mySerialPort->setFlowControl(QSerialPort::NoFlowControl); elseif(FlowCtrlCB->currentText()=="hardware") mySerialPort->setFlowControl(QSerialPort::HardwareControl); elseif(FlowCtrlCB->currentText()=="xonxoff") mySerialPort->setFlowControl(QSerialPort::SoftwareControl); if(FlowCtrlCnt){ statusBar()->showMessage("FlowCtrlsetsuccessfully",2000); } ++FlowCtrlCnt; } } voidBasicTransceiver::resetCnt() { BaudCnt=0; ParityCnt=0; DataBitsCnt=0; StopBitsCnt=0; FlowCtrlCnt=0; } //打开和关闭串口 voidBasicTransceiver::on_connectButton_toggled(boolchecked) { if(checked==true){ mySerialPort=newQSerialPort(this); QStringtempStr=COMCB->currentText(); tempStr.remove("avail",Qt::CaseSensitive); mySerialPort->setPortName(tempStr); if(mySerialPort->open(QIODevice::ReadWrite)){ portIsOpen=true; emitsetBaudRate(); emitsetParity(); emitsetDataBits(); emitsetStopBits(); emitsetFlowCtrl(); statusBar()->showMessage(mySerialPort->portName()+"isopened",2000); emitsetComLabel(); emitenabledSendButton(); emitenabledAutoSend(); COMCB->setEnabled(false); connect(Timer_CP,SIGNAL(timeout()),this,SLOT(checkPort())); Timer_CP->start(1000); connect(mySerialPort,SIGNAL(readyRead()),this,SLOT(readMyCom())); connectButton->setText(QString::fromLocal8Bit("关闭连接")); connectButton->setIcon(QIcon(":/images/close.png")); }else{ QMessageBox::warning(this, QString::fromLocal8Bit("串口打开失败"), QString::fromLocal8Bit("串口不存在或本串口" "已经被占用,请重试!"), QMessageBox::Cancel); connectButton->setChecked(false); return; } }elseif(checked==false){ if(Timer_AS->isActive()){ Timer_AS->stop(); emitresetAutoSendCB(); } if(Timer_CP->isActive())Timer_CP->stop(); Timer_CP->disconnect(); if(mySerialPort->isOpen())mySerialPort->close(); emitdisabledSendButton(); emitdisabledAutoButton(); emitsetComLabel(); emitsetBaudLabel(); resetCnt(); COMCB->setEnabled(true); connectButton->setText(QString::fromLocal8Bit("打开连接")); connectButton->setIcon(QIcon(":/images/open.png")); portIsOpen=false; } } //设置显示串口号和波特率的Label voidBasicTransceiver::setComLabel() { if(mySerialPort->isOpen()){ comLabel->setText(QString(mySerialPort->portName())); }elseif(!mySerialPort->isOpen()){ comLabel->setText(QString::fromLocal8Bit("COM:#")); } } voidBasicTransceiver::setBaudLabel() { if(mySerialPort->isOpen()){ inti_baud=mySerialPort->baudRate(); QStrings_baud; baudLabel->setText(s_baud.setNum(i_baud)); }elseif(!mySerialPort->isOpen()){ baudLabel->setText(QString::fromLocal8Bit("BAUD:#")); } } voidBasicTransceiver::writeToBuf() { QObject*signalSender=sender(); if(signalSender->objectName()=="sendButton_1"){ if(hexRB_1->isChecked()){ writeHex(senderTextEdit_1); }else{ writeChr(senderTextEdit_1); } }elseif(signalSender->objectName()=="sendButton_2"){ if(hexRB_2->isChecked()){ writeHex(senderTextEdit_2); }else{ writeChr(senderTextEdit_2); } }elseif(signalSender->objectName()=="sendButton_3"){ if(hexRB_3->isChecked()){ writeHex(senderTextEdit_3); }else{ writeChr(senderTextEdit_3); } }elseif(signalSender->objectName()=="sendButton_4"){ if(hexRB_4->isChecked()){ writeHex(senderTextEdit_4); }else{ writeChr(senderTextEdit_4); } }elseif(signalSender->objectName()=="sendButton_5"){ if(hexRB_5->isChecked()){ writeHex(senderTextEdit_5); }else{ writeChr(senderTextEdit_5); } } } voidBasicTransceiver::writeHex(QTextEdit*textEdit) { QStringdataStr=textEdit->toPlainText(); //如果发送的数据个数为奇数的,则在前面最后落单的字符前添加一个字符0 if(dataStr.length()%2){ dataStr.insert(dataStr.length()-1,'0'); } QByteArraysendData; StringToHex(dataStr,sendData); mySerialPort->write(sendData); RxLCD->display(RxLCD->value()+sendData.size()); } voidBasicTransceiver::writeChr(QTextEdit*textEdit) { QByteArraysendData=textEdit->toPlainText().toUtf8(); if(!sendData.isEmpty()&&!sendData.isNull()){ mySerialPort->write(sendData); } RxLCD->display(RxLCD->value()+sendData.size()); } voidBasicTransceiver::StringToHex(QStringstr,QByteArray&senddata)//字符串转换为十六进制数据0-F { inthexdata,lowhexdata; inthexdatalen=0; intlen=str.length(); senddata.resize(len/2); charlstr,hstr; for(inti=0;i =len)break; lstr=str[i].toLatin1(); hexdata=ConvertHexChar(hstr); lowhexdata=ConvertHexChar(lstr); if((hexdata==16)||(lowhexdata==16)) break; else hexdata=hexdata*16+lowhexdata; ++i; senddata[hexdatalen]=(char)hexdata; ++hexdatalen; } senddata.resize(hexdatalen); } charBasicTransceiver::ConvertHexChar(charch) { if((ch>='0')&&(ch<='9')) returnch-0x30; elseif((ch>='A')&&(ch<='F')) returnch-'A'+10; elseif((ch>='a')&&(ch<='f')) returnch-'a'+10; elsereturnch-ch; } voidBasicTransceiver::enabledSendButton() { sendButton_1->setEnabled(true); sendButton_2->setEnabled(true); sendButton_3->setEnabled(true); sendButton_4->setEnabled(true); sendButton_5->setEnabled(true); } voidBasicTransceiver::disabledSendButton() { sendButton_1->setEnabled(false); sendButton_2->setEnabled(false); sendButton_3->setEnabled(false); sendButton_4->setEnabled(false); sendButton_5->setEnabled(false); } voidBasicTransceiver::startAutoSend(QPushButton*sendButton) { connect(Timer_AS,SIGNAL(timeout()),sendButton,SIGNAL(clicked())); QStringinterval; if(sendButton->objectName()=="sendButton_1"){ disabledSendButton(); Timer_AS->start(intervalSB_1->value()); statusBar()->showMessage(QString::fromLocal8Bit("每")+interval.setNum(intervalSB_1->value())+QString::fromLocal8Bit("ms自动发送一次"),2000); }elseif(sendButton->objectName()=="sendButton_2"){ disabledSendButton(); Timer_AS->start(intervalSB_2->value()); statusBar()->showMessage(QString::fromLocal8Bit("每")+interval.setNum(intervalSB_2->value())+QString::fromLocal8Bit("ms自动发送一次"),2000); }elseif(sendButton->objectName()=="sendButton_3"){ disabledSendButton(); Timer_AS->start(intervalSB_3->value()); statusBar()->showMessage(QString::fromLocal8Bit("每")+interval.setNum(intervalSB_3->value())+QString::fromLocal8Bit("ms自动发送一次"),2000); }elseif(sendButton->objectName()=="sendButton_4"){ disabledSendButton(); Timer_AS->start(intervalSB_4->value()); statusBar()->showMessage(QString::fromLocal8Bit("每")+interval.setNum(intervalSB_4->value())+QString::fromLocal8Bit("ms自动发送一次"),2000); }elseif(sendButton->objectName()=="sendButton_5"){ disabledSendButton(); Timer_AS->start(intervalSB_5->value()); statusBar()->showMessage(QString::fromLocal8Bit("每")+interval.setNum(intervalSB_5->value())+QString::fromLocal8Bit("ms自动发送一次"),2000); } } voidBasicTransceiver::setConnections() { connect(autoSendCB_1,SIGNAL(stateChanged(int)),this,SLOT(checkAutoSendCB())); connect(autoSendCB_2,SIGNAL(stateChanged(int)),this,SLOT(checkAutoSendCB())); connect(autoSendCB_3,SIGNAL(stateChanged(int)),this,SLOT(checkAutoSendCB())); connect(autoSendCB_4,SIGNAL(stateChanged(int)),this,SLOT(checkAutoSendCB())); connect(autoSendCB_5,SIGNAL(stateChanged(int)),this,SLOT(checkAutoSendCB())); connect(actionWrite_data,SIGNAL(triggered()),this,SLOT(saveAs())); connect(actionRead_data,SIGNAL(triggered()),this,SLOT(open())); connect(actionChoose_file,SIGNAL(triggered()),this,SLOT(open())); connect(exitAction,SIGNAL(triggered()),qApp,SLOT(quit())); connect(actionAbout,SIGNAL(triggered()),qApp,SLOT(aboutQt())); connect(sendButton_1,SIGNAL(clicked()),this,SLOT(writeToBuf())); connect(sendButton_2,SIGNAL(clicked()),this,SLOT(writeToBuf())); connect(sendButton_3,SIGNAL(clicked()),this,SLOT(writeToBuf())); connect(sendButton_4,SIGNAL(clicked()),this,SLOT(writeToBuf())); connect(sendButton_5,SIGNAL(clicked()),this,SLOT(writeToBuf())); connect(BAUDCB,SIGNAL(currentIndexChanged(int)),this,SLOT(setBaudRate())); connect(ParityCB,SIGNAL(currentIndexChanged(int)),this,SLOT(setParity())); connect(DataBitsCB,SIGNAL(currentIndexChanged(int)),this,SLOT(setDataBits())); connect(StopBitsCB,SIGNAL(currentIndexChanged(int)),this,SLOT(setStopBits())); connect(FlowCtrlCB,SIGNAL(currentIndexChanged(int)),this,SLOT(setFlowCtrl())); } voidBasicTransceiver::enabledAutoSend() { autoSendCB_1->setEnabled(true); autoSendCB_2->setEnabled(true); autoSendCB_3->setEnabled(true); autoSendCB_4->setEnabled(true); autoSendCB_5->setEnabled(true); } voidBasicTransceiver::disabledAutoButton() { autoSendCB_1->setEnabled(false); autoSendCB_2->setEnabled(false); autoSendCB_3->setEnabled(false); autoSendCB_4->setEnabled(false); autoSendCB_5->setEnabled(false); } voidBasicTransceiver::resetAutoSendCB() { autoSendCB_1->setChecked(false); autoSendCB_2->setChecked(false); autoSendCB_3->setChecked(false); autoSendCB_4->setChecked(false); autoSendCB_5->setChecked(false); } voidBasicTransceiver::readMyCom() { QByteArraytemp=mySerialPort->readAll(); QStringbuf; if(actionAlways_show->isChecked()){ if(!temp.isEmpty()){ if(chrReceive->isChecked()){ buf=temp; }elseif(hexReceive->isChecked()){ for(inti=0;i setText(receiveTextBrowser->document()->toPlainText()+buf); receiveTextBrowser->moveCursor(QTextCursor::End); //ui->statusBar->showMessage(tr("成功读取%1字节数据").arg(temp.size())); } } TxLCD->display(TxLCD->value()+temp.size()); } //检测可用串口并在可用串口号后面加上可用标志 voidBasicTransceiver::checkAvailablePorts() {//找不到存在串口是不会进入到foreach内部的。。。存在不一定可用 foreach(constQSerialPortInfo&Info,QSerialPortInfo::availablePorts()){ QSerialPortavailablePort; availablePort.setPortName(Info.portName()); if(availablePort.open(QIODevice::ReadWrite)){ intindex=COMCB->findText(Info.portName()); COMCB->setItemText(index,Info.portName()+"avail"); COMCB->setCurrentIndex(index); iVec.push_back(index);//将修改了内容的项索引添加到容器中 checkAPButton->setIcon(QIcon(":/images/find_it.png")); availablePort.close(); } } if(iVec.size()==0){checkAPButton->setIcon(QIcon(":/images/find.png"));} QStringavailPortCnt; statusBar()->showMessage(availPortCnt.setNum(iVec.size())+"availableports",2000); } //将选择串口号的checkBox重置并重新检测可用串口 voidBasicTransceiver::on_checkAPButton_clicked() { if(!iVec.isEmpty()){ for(inti=0;i!=iVec.size();++i){ QStringtempStr; COMCB->setItemText(iVec[i],QString("COM")+ tempStr.setNum(iVec[i])); } COMCB->setCurrentIndex(0); iVec.clear(); } emitcheckAvailablePorts(); } voidBasicTransceiver::checkPort() { QSet portSet; foreach(constQSerialPortInfo&Info,QSerialPortInfo::availablePorts()){ portSet.insert(Info.portName()); } if(portSet.find(mySerialPort->portName())==portSet.end()){ QMessageBox::warning(this, QString::fromLocal8Bit("Applicationerror"), QString::fromLocal8Bit("Failwiththefollowingerror:\n串口访问失败\n\nPort:%1") .arg(mySerialPort->portName()), QMessageBox::Close); emiton_connectButton_toggled(false); } } voidBasicTransceiver::on_resetCntButton_clicked() { RxLCD->display(0); TxLCD->display(0); } voidBasicTransceiver::on_exitButton_clicked() { qApp->quit(); } //另存为 boolBasicTransceiver::saveAs() { QStringfileName=QFileDialog::getSaveFileName(this, tr("SaveData"),".", tr("TextFile(*.txt)")); if(fileName.isEmpty()){ returnfalse; } returnsaveFile(fileName); } //保存文件 boolBasicTransceiver::saveFile(constQString&fileName) { if(!writeFile(fileName)){ statusBar()->showMessage(tr("Savingcanceled"),2000); returnfalse; } statusBar()->showMessage(tr("Datasaved"),2000); returntrue; } boolBasicTransceiver::writeFile(constQString&fileName) { QFilefile(fileName); if(!file.open(QIODevice::WriteOnly|QFile::Text)){ QMessageBox::warning(this,tr("SaveData"), tr("Cannotwritefile%1:\n%2") .arg(file.fileName()) .arg(file.errorString())); returnfalse; } QTextStreamout(&file); out< toPlainText(); returntrue; } //打开文件的函数 voidBasicTransceiver::open() { QStringfileName=QFileDialog::getOpenFileName(this, tr("ChooseTextFile"),".", tr("TextFile(*.txt)")); if(!fileName.isEmpty()){ loadFile(fileName); } } //加载文件 boolBasicTransceiver::loadFile(constQString&fileName) { if(!readFile(fileName)){ statusBar()->showMessage(tr("Loadingcanceled"),2000); returnfalse; } statusBar()->showMessage(tr("Dataloaded"),2000); returntrue; } //读取文件 boolBasicTransceiver::readFile(constQString&fileName) { QFilefile(fileName); if(!file.open(QIODevice::ReadOnly)){ QMessageBox::warning(this,tr("Readfailed"), tr("Cannotreadfile%1:\n%2.") .arg(file.fileName()) .arg(file.errorString())); returnfalse; } QTextStreamin(&file); QObject*signalSender=sender(); if(signalSender->objectName()=="actionRead_data"){ receiveTextBrowser->setText(in.readAll()); }elseif(signalSender->objectName()=="actionChoose_file"){ senderTextEdit_1->setText(in.readAll()); } returntrue; } voidBasicTransceiver::dragEnterEvent(QDragEnterEvent*event) { if(event->mimeData()->hasFormat("text/uri-list")) event->acceptProposedAction(); } voidBasicTransceiver::dropEvent(QDropEvent*event) { QList urls=event->mimeData()->urls(); if(urls.isEmpty()) return; QStringfileName=urls.first().toLocalFile(); if(fileName.isEmpty()){ return; } loadFile(fileName); }
程序完全是面向对象的,每个功能都是用相应函数实现的,这也提高了函数的重用性。
本文是一个完整的Qt串口通信模块QSerialPort开发完整实例,感兴趣的可以细细阅读源码内容,更多关于Qt串口通信知识请查看下面的相关链接
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。