117 lines
3.0 KiB
C++
117 lines
3.0 KiB
C++
#include "mainwindow.h"
|
||
#include "ui_mainwindow.h"
|
||
|
||
|
||
//构造函数,用于初始化
|
||
MainWindow::MainWindow(QMainWindow *parent) : QMainWindow(parent)
|
||
, ui(new Ui::MainWindow){
|
||
|
||
ui->setupUi(this);
|
||
//初始化串口
|
||
serial = new QSerialPort(this);
|
||
initSerialPorts();
|
||
//连接信号与串口
|
||
//是谁,谁发出信息,在哪里,谁接收信号
|
||
connect(serial,&QSerialPort::readyRead,this,&MainWindow::readData);
|
||
|
||
}
|
||
|
||
//析构函数,释放资源
|
||
MainWindow::~MainWindow()
|
||
{
|
||
|
||
if (serial) {
|
||
if (serial->isOpen()) {
|
||
serial->close();
|
||
}
|
||
delete serial;
|
||
serial = nullptr; // 防止悬空指针
|
||
}
|
||
delete ui;
|
||
|
||
}
|
||
|
||
//更新串口信息
|
||
// *********portComboBox怎么使用***************
|
||
void MainWindow::updateSerialPortsList()
|
||
{
|
||
ui->portComboBox->clear();
|
||
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
|
||
ui->portComboBox->addItem(info.portName());
|
||
}
|
||
}
|
||
|
||
|
||
|
||
//初始化串口————成员函数
|
||
void MainWindow::initSerialPorts()
|
||
{
|
||
//更新串口信息成员函数,在上面定义
|
||
updateSerialPortsList();
|
||
|
||
//设置串口参数初始化
|
||
serial->setBaudRate(QSerialPort::Baud9600);
|
||
serial->setDataBits(QSerialPort::Data8);
|
||
serial->setParity(QSerialPort::NoParity);
|
||
serial->setStopBits(QSerialPort::OneStop);
|
||
serial->setFlowControl(QSerialPort::NoFlowControl);
|
||
}
|
||
|
||
|
||
|
||
//按钮槽函数,QT框架自动实现
|
||
|
||
//打开或关闭串口
|
||
void MainWindow::on_openCloseButton_clicked()
|
||
{
|
||
if (serial->isOpen()) {
|
||
serial->close();
|
||
ui->openCloseButton->setText("打开串口");
|
||
statusBar()->showMessage("串口已关闭");
|
||
} else {
|
||
serial->setPortName(ui->portComboBox->currentText());
|
||
if (serial->open(QIODevice::ReadWrite)) {
|
||
ui->openCloseButton->setText("关闭串口");
|
||
statusBar()->showMessage("串口已打开");
|
||
} else {
|
||
QMessageBox::critical(this, "错误", "无法打开串口");
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
|
||
|
||
//发送数据
|
||
void MainWindow::on_sendButton_clicked()
|
||
{
|
||
if (serial->isOpen()) {
|
||
|
||
if (serial->isOpen()) {
|
||
QString text = ui->sendTextEdit->toPlainText();
|
||
for (int i = 0; i < text.length(); i++) {
|
||
QByteArray data;
|
||
data.append(QString(text[i]).toUtf8()); // 逐个字符发送
|
||
serial->write(data);
|
||
QThread::msleep(100); // 可选:增加延迟以避免发送过快
|
||
}
|
||
if(serial->flush())
|
||
ui->sendTextEdit->clear();// 确保所有数据发送完成
|
||
|
||
|
||
} else {
|
||
QMessageBox::warning(this, "警告", "请先打开串口");
|
||
}
|
||
|
||
}
|
||
}
|
||
|
||
|
||
|
||
//串口接收数据槽函数
|
||
void MainWindow::readData()
|
||
{
|
||
QByteArray data = serial->readAll();
|
||
ui->receiveTextEdit->appendPlainText(QString::fromUtf8(data));
|
||
}
|