.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSerialPortInfo>
#include <QTimer>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void Read_Serial_Connect_Success();
void Timer0_Init();
QTimer *myTime;
void Serial_Connect_Success_Label_Text();
void Serial_Connect_NG_Label_Text();
private slots:
void Timer0_Task();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
.c
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QTime>
#include <string>
#include <iostream>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
Timer0_Init();
//设置标题栏
MainWindow::setWindowTitle(tr("自动识别串口连接Demo"));
//设置窗口为白色
QPalette palette(this->palette());
palette.setColor(QPalette::Background, Qt::white);
this->setPalette(palette);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::Timer0_Init()
{
myTime = new QTimer();
myTime->stop();
myTime->setInterval(500);//1ms定时器,类似于单片机的中断函数
connect(myTime,SIGNAL(timeout()),this,SLOT(Timer0_Task()));
myTime->start();
}
//串口自动识别部分
static int Read_Serial_Port_Info()
{
const QString Read_Serial_Port_Info_Buff = "USB-SERIAL CH340";
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
qDebug() << "Name : " << info.portName();
qDebug() << "Description :"<<info.description();
if(Read_Serial_Port_Info_Buff == info.description())
return true;
else
return false;
}
return false;
}
void MainWindow::Read_Serial_Connect_Success()
{
qDebug() << Read_Serial_Port_Info() << endl;
if(Read_Serial_Port_Info())
Serial_Connect_Success_Label_Text();
else
Serial_Connect_NG_Label_Text();
}
void MainWindow::Timer0_Task()
{
Read_Serial_Connect_Success();
}
void MainWindow::Serial_Connect_Success_Label_Text()
{
ui->label->setText("串口已经连接");
QPalette pe;
pe.setColor(QPalette::WindowText,Qt::red);
ui->label->setPalette(pe);
}
void MainWindow::Serial_Connect_NG_Label_Text()
{
ui->label->setText("串口等待连接");
QPalette pe;
pe.setColor(QPalette::WindowText,Qt::black);
ui->label->setPalette(pe);
}
如果有问题欢迎询问。