1.pro文件
QT += core gui serialport
2.mainwindow.h
#pragma execution_character_set("utf-8")//格式转换,防止乱码
3. mainwindow.cpp
connect(serialPort,&QSerialPort::readyRead,this,&MainWindow::receiveInformation);
4.on_pushButtonSend_clicked
void MainWindow::on_pushButtonSend_clicked()
{
QString content = ui->textEditBottom->toPlainText();
if(serialPort->isOpen()){
if(!content.isEmpty()){
if(ui->checkBoxOpenFile->isChecked()){
QFile file(content);
if(file.open(QIODevice::ReadOnly)){
QByteArray data = file.readAll();
file.close();
ui->textEditTop->append("选择了文件:"+content+"\n"+"文件内容为:\n");
QString str;
if(ui->radioButtonSendAscii->isChecked()){
str = stringToAscii(data);
sendInformation(str);
}
else if(ui->radioButtonSendHexadecimal->isChecked()){
str = stringToHex(data);
sendInformation(str);
}
else{
str = data;
sendInformation(str);
}
ui->textEditTop->append(str);
}
else{
QString fileOpeningFailed = "文件打开失败";
qDebug() <<fileOpeningFailed;
}
addToHistory(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"), "发送信息", content);
}
else{
QString str = content;
sendInformation(str);
ui->textEditTop->append(str);
addToHistory(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"), "发送信息", str);
}
}
else{
QString contentIsEmpty = "\n要发送的内容为空,请添加内容";
ui->textEditTop->append(contentIsEmpty);
qDebug() <<contentIsEmpty;
}
}
else{
QString serialPortIsNotOpend = "串口未打开";
ui->textEditTop->append(serialPortIsNotOpend);
}
}
5 .sendInformation
void MainWindow::sendInformation(QString str)
{
qint64 totalBytes = str.size();
qint64 bytesWritten = 0;
while (bytesWritten<totalBytes) {
qint64 bytesToWrite = qMin(static_cast<qint64>(64), totalBytes - bytesWritten);
qint64 bytesActuallyWritten = serialPort->write(str.mid(bytesWritten, bytesToWrite).toUtf8());
if(bytesActuallyWritten == -1 || bytesActuallyWritten == 0){
break;
}
bytesWritten += bytesActuallyWritten;
if (serialPort->isOpen() && serialPort->canReadLine()) {
QByteArray line = serialPort->readLine();
QString receivedData = QString::fromUtf8(line);
QString sentNumberOfBytes = "发送了" + receivedData + "字节";
ui->textEditTop->append(sentNumberOfBytes);
}
}
}
6.receiveInformation
void MainWindow::receiveInformation()
{
QByteArray data = serialPort->readAll();
receiveData = data;
QDateTime currentTime = QDateTime::currentDateTime();
QString timeStr = currentTime.toString("yyyy-mm-dd hh:mm:ss");
QString str = timeStr + QString("接受到以下信息:");
ui->textEditTop->append(str);
if(ui->radioButtonAcceptAscii->isChecked()){
QString asciiStr = stringToAscii(data);
ui->textEditTop->append(asciiStr);
ui->textEditTop->append("\n");
addToHistory(timeStr, "接收信息", asciiStr);
}
else if(ui->radioButtonAcceptHexadecimal->isChecked()){
QString hexStr = stringToHex(data);
ui->textEditTop->append(hexStr);
ui->textEditTop->append("\n");
addToHistory(timeStr, "接收信息", hexStr);
}
else{
ui->textEditTop->append(data);
ui->textEditTop->append("\n");
addToHistory(timeStr, "接收信息", data);
}
}
7.on_pushButtonOpen_clicked
void MainWindow::on_pushButtonOpen_clicked()
{
serialPort->setBaudRate(ui->comboBoxBaudRate->currentText().toInt());
serialPort->setPortName(ui->comboBoxSerialPort->currentText());
QString stopBitText = ui->comboBoxStopBit->currentText();
QSerialPort::StopBits stopBits = QSerialPort::UnknownStopBits;
if (stopBitText == "OneStop") {
stopBits = QSerialPort::OneStop;
}
else if (stopBitText == "OneAndHalfStop") {
stopBits = QSerialPort::OneAndHalfStop;
}
else if (stopBitText == "TwoStop") {
stopBits = QSerialPort::TwoStop;
}
serialPort->setStopBits(stopBits);
QString parityBitText = ui->comboBoxParityBit->currentText();
QSerialPort::Parity partyBits = QSerialPort::UnknownParity;
if(parityBitText == "NoParity"){
partyBits = QSerialPort::NoParity;
}
else if(parityBitText == "OddParity"){
partyBits = QSerialPort::OddParity;
}
else if(parityBitText == "EvenParity"){
partyBits = QSerialPort::EvenParity;
}
else if(parityBitText == "MarkParity"){
partyBits = QSerialPort::MarkParity;
}
else if(parityBitText == "SpaceParity"){
partyBits = QSerialPort::SpaceParity;
}
serialPort->setParity(partyBits);
QString dataBitText = ui->comboBoxDataBit->currentText();
QSerialPort::DataBits dataBits = QSerialPort::UnknownDataBits;
if(dataBitText == "5"){
dataBits = QSerialPort::Data5;
}
else if(dataBitText == "6"){
dataBits = QSerialPort::Data6;
}
else if(dataBitText == "7"){
dataBits = QSerialPort::Data7;
}
else if(dataBitText == "8"){
dataBits = QSerialPort::Data8;
}
serialPort->setDataBits(dataBits);
QString flowControlText = ui->comboBoxFlowControl->currentText();
QSerialPort::FlowControl flowControl = QSerialPort ::UnknownFlowControl;
if(flowControlText == "NoFlowControl"){
flowControl = QSerialPort::NoFlowControl;
}
else if(flowControlText == "HardwareControl"){
flowControl = QSerialPort::HardwareControl;
}
else if(flowControlText == "SoftwareControl"){
flowControl = QSerialPort::SoftwareControl;
}
serialPort->setFlowControl(flowControl);
QString selectPortName = ui->comboBoxSerialPort->currentText();
QString str1 = "串口"+selectPortName+"打开成功";
QString str2 = "串口"+selectPortName+"打开失败";
serialPort->open(QIODevice::ReadWrite);
if(serialPort->isOpen()){
qDebug() << str1;
ui->plainTextEdit->appendPlainText(str1);
comboBoxStatus(false);
ui->pushButtonSerialPortOpen->setEnabled(false);
ui->pushButtonSerialPortClose->setEnabled(true);
QSettings settings;
settings.beginGroup("SerialPortSettings");
settings.setValue("PortName",ui->comboBoxSerialPort->currentText());
settings.setValue("BaudRate",ui->comboBoxBaudRate->currentText());
settings.setValue("StopBits", stopBitText);
settings.setValue("Parity", parityBitText);
settings.setValue("DataBits", dataBitText);
settings.endGroup();
}
else{
qDebug() << str2;
ui->plainTextEdit->appendPlainText(str2);
}
}
8.on_pushButtonClose_clicked
void MainWindow::on_pushButtonClose_clicked()
{
serialPort->close();
QString selectPortName = ui->comboBox->currentText();
QString str1 = "串口"+selectPortName+"关闭失败";
QString str2 = "串口"+selectPortName+"关闭成功";
if(serialPort->isOpen()){
qDebug() << str1;
ui->textEditTop->append(str1);
}
else{
comboBoxStatus(true);
qDebug() << str2;
ui->textEditTop->append(str2);
}
updateSerialPort();
}
9.updateSerialPort
void MainWindow::updateSerialPort()
{
ui->comboBox->clear();
foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts()){
QStringList serialNamePort;
serialNamePort<<info.portName();
ui->comboBox->addItem(info.portName());
}
}
10.
11.mainwindow .h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFontMetrics>
#include <QVBoxLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QWidget>
#include <QResizeEvent>
#include <QSize>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QIODevice>
#include <QtDebug>
#include <QFile>
#include <QByteArray>
#include <QMessageBox>
#include <QByteArray>
#include <QDateTime>
#include <QFileDialog>
#include <QButtonGroup>
#include <QProcess>
#include <QPaintEvent>
#include <QPainter>
#include <QDesktopWidget>
#include <QUrl>
#include <QDesktopServices>
#include <QTimer>
#include <QTableWidget>
#include <QVector>
#include <QDateTime>
#include <qmetatype.h>
#include <historywindow.h>
#pragma execution_character_set("utf-8")
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
public:
QString originalData;
QString previousFilePath;
QString openFilePath;
private slots:
void on_pushButtonOpen_clicked();
void on_pushButtonTop_clicked();
void on_pushButtonBottom_clicked();
void on_pushButtonSend_clicked();
void on_pushButtonClose_clicked();
void on_checkBoxSaveFile_clicked();
void on_checkBoxOpenFile_clicked();
void on_radioButtonSendAscii_clicked();
void on_radioButtonSendHexadecimal_clicked();
void on_radioButtonSendString_clicked();
void on_actionnewWindows_triggered();
// void onButtonMinClicked();
// void onButtonRestoreClicked();
// void onButtonMaxClicked();
// void onButtonCloseClicked();
// void on_actiontopmost_changed();
void on_actionASCIICharacterTable_triggered();
void on_actionquit_triggered();
void on_comboBox_currentTextChanged(const QString &arg1);
// void initEventFilters();
// bool eventFilter(QObject *watched, QEvent *event);
void addToHistory(const QString& time, const QString& event, const QString& details);
void on_actionhistory_triggered();
private:
Ui::MainWindow * ui;
QSerialPort * serialPort;
QString receiveData;
QButtonGroup * sendButtonGroup;
QLabel * mousePositionLabel;
// QTableWidget * historyTableWidget;
// QVector<QString> historyReccords;
private:
void updateSerialPort();
void closeEvent();
void comboBoxStatus(bool openEnabled);
void receiveInformation();
QString stringToAscii(const QString &str);
QString stringToHex(const QString &str);
void sendInformation(QString str);
void updateWindowTitle();
void initHistoryTable();
// void initTitleBar();
// void paintEvent(QPaintEvent * event);
// void loadStyleSheet(const QString &sheetName);
};
#endif // MAINWINDOW_H
12.mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
//#include "historywindow.h"
#include "ui_historywindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
serialPort = new QSerialPort;
mousePositionLabel = new QLabel(this);
setWindowIcon(QIcon("G:\\tangchenyun\\new\\image\\Serial_port_assistant.png"));
ui->pushButtonClose->setEnabled(false);
ui->radioButtonAcceptString->setChecked(true);
ui->radioButtonSendString->setChecked(true);
updateSerialPort();
ui->textEditTop->setText("请先选择串口和波特率,在打开串口");
connect(serialPort,&QSerialPort::readyRead,this,&MainWindow::receiveInformation);
QTextCursor cursor = ui->textEditTop->textCursor();
cursor.movePosition(QTextCursor::End);
ui->textEditTop->setTextCursor(cursor);
ui->menuset->setTitle("串口设置");
ui->menuset->setIcon(QIcon("G:\\tangchenyun\\new\\image\\串口设置.png"));
// this ->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMaximizeButtonHint);
// setAttribute(Qt::WA_TranslucentBackground);
// setAttribute(Qt::WA_DeleteOnClose);
// initTitleBar();
}
MainWindow::~MainWindow()
{
delete ui;
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~更新串口,窗口~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void MainWindow::updateSerialPort()
{
ui->comboBox->clear();
foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts()){
QStringList serialNamePort;
serialNamePort<<info.portName();
ui->comboBox->addItem(info.portName());
}
}
void MainWindow::updateWindowTitle()
{
setWindowTitle(ui->comboBox->currentText());
}
void MainWindow::on_comboBox_currentTextChanged(const QString &arg1)
{
updateWindowTitle();
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~开关串口~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void MainWindow::on_pushButtonOpen_clicked()
{
serialPort->setBaudRate(ui->comboBox_2->currentText().toInt());
serialPort->setPortName(ui->comboBox->currentText());
QString selectPortName = ui->comboBox->currentText();
QString str1 = "串口"+selectPortName+"打开成功";
QString str2 = "串口"+selectPortName+"打开失败";
serialPort->open(QIODevice::ReadWrite);
if(serialPort->isOpen()){
comboBoxStatus(false);
qDebug() << str1;
ui->textEditTop->append(str1);
}
else{
qDebug() << str2;
ui->textEditTop->append(str2);
}
}
void MainWindow::on_pushButtonClose_clicked()
{
serialPort->close();
QString selectPortName = ui->comboBox->currentText();
QString str1 = "串口"+selectPortName+"关闭失败";
QString str2 = "串口"+selectPortName+"关闭成功";
if(serialPort->isOpen()){
qDebug() << str1;
ui->textEditTop->append(str1);
}
else{
comboBoxStatus(true);
qDebug() << str2;
ui->textEditTop->append(str2);
}
updateSerialPort();
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~发送和接受~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void MainWindow::on_pushButtonSend_clicked()
{
QString content = ui->textEditBottom->toPlainText();
if(serialPort->isOpen()){
if(!content.isEmpty()){
if(ui->checkBoxOpenFile->isChecked()){
QFile file(content);
if(file.open(QIODevice::ReadOnly)){
QByteArray data = file.readAll();
file.close();
ui->textEditTop->append("选择了文件:"+content+"\n"+"文件内容为:\n");
QString str;
if(ui->radioButtonSendAscii->isChecked()){
str = stringToAscii(data);
sendInformation(str);
}
else if(ui->radioButtonSendHexadecimal->isChecked()){
str = stringToHex(data);
sendInformation(str);
}
else{
str = data;
sendInformation(str);
}
ui->textEditTop->append(str);
}
else{
QString fileOpeningFailed = "文件打开失败";
qDebug() <<fileOpeningFailed;
}
addToHistory(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"), "发送信息", content);
}
else{
QString str = content;
sendInformation(str);
ui->textEditTop->append(str);
//addToHistory(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"), "发送信息", str);
}
}
else{
QString contentIsEmpty = "\n要发送的内容为空,请添加内容";
ui->textEditTop->append(contentIsEmpty);
qDebug() <<contentIsEmpty;
}
}
else{
QString serialPortIsNotOpend = "串口未打开";
ui->textEditTop->append(serialPortIsNotOpend);
}
}
void MainWindow::receiveInformation()
{
QByteArray data = serialPort->readAll();
receiveData = data;
QDateTime currentTime = QDateTime::currentDateTime();
QString timeStr = currentTime.toString("yyyy-mm-dd hh:mm:ss");
QString str = timeStr + QString("接受到以下信息:");
ui->textEditTop->append(str);
if(ui->radioButtonAcceptAscii->isChecked()){
QString asciiStr = stringToAscii(data);
ui->textEditTop->append(asciiStr);
ui->textEditTop->append("\n");
//addToHistory(timeStr, "接收信息", asciiStr);
}
else if(ui->radioButtonAcceptHexadecimal->isChecked()){
QString hexStr = stringToHex(data);
ui->textEditTop->append(hexStr);
ui->textEditTop->append("\n");
//addToHistory(timeStr, "接收信息", hexStr);
}
else{
ui->textEditTop->append(data);
ui->textEditTop->append("\n");
//addToHistory(timeStr, "接收信息", data);
}
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~工具栏~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void MainWindow::on_actionnewWindows_triggered()
{
QProcess p(this);
p.startDetached(QApplication::applicationName());
}
//void MainWindow::on_actiontopmost_changed()
//{
// if(ui->actiontopmost->isCheckable()){
// QMainWindow * window = this;
// Qt::WindowFlags flags = window->windowFlags();
// if(ui->actiontopmost->isChecked()){
// window->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
// }
// else {
// window->setWindowFlags(flags & ~Qt::WindowStaysOnTopHint);
// }
// }
//}
void MainWindow::on_actionASCIICharacterTable_triggered()
{
QString command ;
QStringList arguments;
#ifdef Q_OS_WINDOWS
command = "cmd";
arguments << "/c" << "start" << "https://www.asciim.cn/";
#elif defined(Q_OS_LINUX)
command = "xdg-open";
arguments<<"https://www.asciim.cn/";
#endif
QProcess::startDetached(command,arguments);
// QUrl url("https://www.asciim.cn/");
// QDesktopServices::openUrl(url);
}
void MainWindow::on_actionquit_triggered()
{
on_pushButtonTop_clicked();
}
///*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~标题框~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
//void MainWindow::onButtonMinClicked()
//{
// showMinimized();
//}
//void MainWindow::onButtonRestoreClicked()
//{
// QPoint windosPos;
// QSize windowSize;
// m_titleBar->getRestoreInfo(windosPos,windowSize);
// this->setGeometry(QRect(windosPos,windowSize));
//}
//void MainWindow::onButtonMaxClicked()
//{
// m_titleBar->saveRestoreInfo(this->pos(),QSize(this->width(),this->height()));
// QRect desktopRect = QApplication::desktop()->availableGeometry();
// QRect factRect = QRect(desktopRect.x()-3,desktopRect.y()-3,desktopRect.width()+6,desktopRect.height()+6);
// setGeometry(factRect);
//}
//void MainWindow::onButtonCloseClicked()
//{
// this->close();
//}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~打开保存文件~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void MainWindow::on_checkBoxSaveFile_clicked()
{
if(ui->checkBoxSaveFile->isChecked()){
QString filePath = QFileDialog::getSaveFileName(this,"选择文件","", "所有文件 (*)");
if(!filePath.isEmpty()){
ui->checkBoxSaveFile->setChecked(true);
QMessageBox msg;
msg.setText("选择保存方式");
msg.setInformativeText("你想要覆盖现有文件还是续写?");
msg.addButton("续写", QMessageBox::ActionRole);
msg.addButton("覆盖", QMessageBox::ActionRole);
int ret = msg.exec();
QFile file(filePath);
QTextStream out(&file);
switch (ret) {
case 0:
if(file.open(QIODevice::Append)){
out << "\n" << receiveData;
}
break;
case 1:
if(file.open(QIODevice::WriteOnly)){
out << receiveData;
}
break;
}
previousFilePath = filePath;
}
else{
ui->checkBoxSaveFile->setChecked(false);
}
}
}
void MainWindow::on_checkBoxOpenFile_clicked()
{
QString str;
if(ui->checkBoxOpenFile->isChecked()){
QString filePath = QFileDialog::getOpenFileName(this,"选择文件","", "所有文件 (*)");
if(!filePath.isEmpty()){
ui->checkBoxOpenFile->setChecked(true);
QString str = QString("引用原文件:")+"\n"+filePath+"\n\n\n";
ui->textEditBottom->setText(filePath);
ui->textEditTop->append(str);
openFilePath = filePath;
}
else{
ui->checkBoxOpenFile->setChecked(false);
}
if(ui->checkBoxOpenFile->isChecked() == false){
QString text = ui->textEditBottom->toPlainText();
text.remove(str);
ui->textEditBottom->setText(text);
}
}
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~清除信息~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void MainWindow::on_pushButtonTop_clicked()
{
ui->textEditTop->clear();
}
void MainWindow::on_pushButtonBottom_clicked()
{
if(ui->checkBoxOpenFile->isChecked()){
ui->checkBoxOpenFile->setChecked(false);
}
ui->textEditBottom->clear();
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~关闭窗口~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void MainWindow::closeEvent()
{
if(serialPort->isOpen()){
QMessageBox::warning(this,"串口未关闭","强制关闭串口");
serialPort->close();
}
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~格式转换~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void MainWindow::on_radioButtonSendAscii_clicked()
{
originalData = ui->textEditBottom->toPlainText();
QString strToAscii = stringToAscii(originalData);
ui->textEditBottom->clear();
ui->textEditBottom->setText(strToAscii);
ui->textEditTop->append("\n\t5秒后显示原始数据");
QTimer * timer = new QTimer(this);
connect(timer,&QTimer::timeout,this,[this](){
ui->textEditBottom->setText(originalData);
});
timer->setSingleShot(true);
timer->start(5000);
}
void MainWindow::on_radioButtonSendHexadecimal_clicked()
{
originalData = ui->textEditBottom->toPlainText();
QString strToHex = stringToHex(originalData);
ui->textEditBottom->clear();
ui->textEditBottom->setText(strToHex);
ui->textEditTop->append("5秒后显示原始数据");
QTimer * timer = new QTimer(this);
connect(timer,&QTimer::timeout,this,[this](){
ui->textEditBottom->setText(originalData);
});
timer->setSingleShot(true);
timer->start(5000);
}
void MainWindow::on_radioButtonSendString_clicked()
{
originalData = ui->textEditBottom->toPlainText();
ui->textEditBottom->clear();
ui->textEditBottom->setText(originalData);
}
QString MainWindow::stringToAscii(const QString &str)
{
QString asciStr;
for (int i=0 ;i<str.length() ;++i ) {
QChar ch = str.at(i);
asciStr += QString::number(ch.toLatin1(),10)+"";
if(i>0){
asciStr +=" ";
}
}
return asciStr;
}
QString MainWindow::stringToHex(const QString &str)
{
QString hexStr;
for (int i =0;i<str.length() ;++i ) {
QChar ch = str.at(i);
QString hexValue = QString("%1").arg(ch.unicode(),2,6,QChar('0'));
if(i>0){
hexStr +=" ";
}
hexStr += hexValue;
}
return hexStr;
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~功能函数~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void MainWindow::comboBoxStatus(bool openEnabled)
{
ui->pushButtonOpen->setEnabled(openEnabled);
ui->comboBox->setEnabled(openEnabled);
ui->comboBox_2->setEnabled(openEnabled);
ui->comboBox_3->setEnabled(openEnabled);
ui->comboBox_4->setEnabled(openEnabled);
ui->comboBox_5->setEnabled(openEnabled);
ui->comboBox_6->setEnabled(openEnabled);
ui->pushButtonClose->setEnabled(!openEnabled);
}
void MainWindow::sendInformation(QString str)
{
qint64 totalBytes = str.size();
qint64 bytesWritten = 0;
while (bytesWritten<totalBytes) {
qint64 bytesToWrite = qMin(static_cast<qint64>(64), totalBytes - bytesWritten);
qint64 bytesActuallyWritten = serialPort->write(str.mid(bytesWritten, bytesToWrite).toUtf8());
if(bytesActuallyWritten == -1 || bytesActuallyWritten == 0){
break;
}
bytesWritten += bytesActuallyWritten;
if (serialPort->isOpen() && serialPort->canReadLine()) {
QByteArray line = serialPort->readLine();
QString receivedData = QString::fromUtf8(line);
QString sentNumberOfBytes = "发送了" + receivedData + "字节";
ui->textEditTop->append(sentNumberOfBytes);
}
}
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~标题框~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/*
void MainWindow::initTitleBar()
{
m_titleBar = new myTitleBar(this);
m_titleBar->move(0,0);
connect(m_titleBar ,SIGNAL(signalButtonMinClicked()),this,SLOT(onButtonMinClicked()));
connect(m_titleBar ,SIGNAL(signalButtonRestoreClicked()),this,SLOT(onButtonRestoreClicked()));
connect(m_titleBar ,SIGNAL(signalButtonMaxClicked()),this,SLOT(onButtonMaxClicked()));
connect(m_titleBar ,SIGNAL(signalButtonCloseClicked()),this,SLOT(onButtonCloseClicked()));
}
void MainWindow::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QPainterPath pathBack;
pathBack.setFillRule(Qt::WindingFill);
pathBack.addRoundedRect(QRect(0,0,this->width(),this->height()),3,3);
painter.setRenderHint(QPainter::SmoothPixmapTransform , true);
painter.fillPath(pathBack,QBrush(QColor(238,223,204)));
return QWidget::paintEvent(event);
}
void MainWindow::loadStyleSheet(const QString &sheetName)
{
QFile file(":/Resources/"+sheetName+".css");
if (file.open(QIODevice::ReadOnly)) {
QString styleSheet = this->styleSheet();
styleSheet += QLatin1String(file.readAll());
this->setStyleSheet(styleSheet);
file.close();
} else {
qDebug() << "Failed to open style sheet file: " << sheetName;
}
}
*/
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~历史记录~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void MainWindow::on_actionhistory_triggered()
{
historywindow * historywin = new historywindow();
historywin->show();
}
void MainWindow::addToHistory(const QString &time, const QString &event, const QString &details)
{
historywindow * historywin = new historywindow;
QTableWidget* tableWidget = historywin->getUi()->tableWidget;
int row = tableWidget->rowCount();
tableWidget->insertRow(row);
tableWidget->setItem(row, 0, new QTableWidgetItem(time));
tableWidget->setItem(row, 1, new QTableWidgetItem(event));
tableWidget->setItem(row, 2, new QTableWidgetItem(details));
}