QT串口助手(五):文件操作 (2)

关于QVector:QVector类是一个提供动态数组的模板类。QVector是Qt的通用容器类之一,它将其项存储在相邻的内存位置并提供基于索引的快速访问。例如上面代码定义了一个大小为filelen的char类型的数组用来储存读取的二进制数据(相对与普通数组而言,QVector数组项可以动态增加,能够避免访问越界等问题)。

QT中使用QTextStream或QIODevice类读写普通文本文件,使用QDataStream类读写二进制文本文件

最后将读取到的文件大小信息和内容显示到接收框并标记有待发送文件:

//显示文件大小信息 QString info = QString("%1%2").arg("文件大小为:").arg(FileText.length()); ui->Receive_TextEdit->clear(); ui->Receive_TextEdit->append(info); //显示文件内容 if (ui->HexDisp_checkBox->isChecked()) { ui->Receive_TextEdit->setPlainText(FileText.toUtf8().toHex(' ').toUpper()); } else { ui->Receive_TextEdit->setPlainText(FileText); } //设置显示焦点在最顶部 ui->Receive_TextEdit->moveCursor(QTextCursor::Start,QTextCursor::MoveAnchor); /*标记有文件发送*/ isSendFile = true; FrameCount = 0; ProgressBarValue = 0; 2.4、文件发送

此时在标记了有文件发送的情况下,点击发送按钮则是发送文件:

/* 函 数:on_Send_Bt_clicked 描 述:发送按键点击信号槽 输 入:无 输 出:无 */ void Widget::on_Send_Bt_clicked() { if (isSerialOpen != false) { if (isSendFile) //发送文件数据 { if (ui->Send_Bt->text() == "发送") { ui->Send_Bt->setText("停止"); SendFile(); } else { ui->Send_Bt->setText("发送"); FileSendTimer->stop(); } } else //发送发送框数据 { SerialSendData(SendTextEditBa); } } else { QMessageBox::information(this, "提示", "串口未打开"); } } /* 函 数:SendData 描 述:定时器发送文件 输 入:无 输 出:无 */ void Widget::SendFile(void) { /*按设置参数发送*/ FrameLen = ui->PackLen_lineEdit->text().toInt(); // 帧大小 FrameGap = ui->GapTim_lineEdit->text().toInt(); // 帧间隔 int textlen = Widget::FileText.size(); // 文件大小 if (FrameGap <= 0 || textlen <= FrameLen) { //时间间隔为0 或 帧大小≥文件大小 则直接一次发送 serial->write(FileText.toUtf8()); ui->Send_Bt->setText("发送"); } else { //按设定时间和长度发送 FrameNumber = textlen / FrameLen; // 包数量 LastFrameLen = textlen % FrameLen; // 最后一包数据长度 //进度条步进值 if (FrameNumber >= 100) { ProgressBarStep = FrameNumber / 100; } else { ProgressBarStep = 100 / FrameNumber; } //设置定时器 FileSendTimer->start(FrameGap); } }

设置一个定时器,将文件按照设定的帧大小和帧间隔来发送:

/*文件帧发送定时器信号槽*/ FileSendTimer = new QTimer(this); connect(FileSendTimer,SIGNAL(timeout()),this,SLOT(File_TimerSend())); /* 函 数:File_TimerSend 描 述:发送文件定时器槽函数 输 入:无 输 出:无 */ void Widget::File_TimerSend(void) { if (FrameCount < FrameNumber) { serial->write(FileText.mid(FrameCount * FrameLen, FrameLen).toUtf8()); FrameCount++; //更新进度条 ui->progressBar->setValue(ProgressBarValue += ProgressBarStep); } else { if (LastFrameLen > 0) { serial->write(FileText.mid(FrameCount * FrameLen, LastFrameLen).toUtf8()); ui->progressBar->setValue(100); } /*发送完毕*/ FileSendTimer->stop(); FrameCount = 0; ProgressBarValue = 0; FrameNumber = 0; LastFrameLen = 0; QMessageBox::information(this, "提示", "发送完成"); ui->progressBar->setValue(0); ui->Send_Bt->setText("发送"); } }

QString QString::mid(int position, int n = -1) const

Returns a string that contains n characters of this string, starting at the specified position index.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzgzdj.html