QT實現簡易串列埠助手

记录学习的Lyx發表於2024-06-24

簡易串列埠助手介面設計

自定義了QWidget的派生類SerialPortWidget,其介面設計大致如下:

QT實現簡易串列埠助手

效果圖:

QT實現簡易串列埠助手

專案結構

serial_port
  └─│  main.cpp					//主程式
    │  mainwindow.cpp			//主視窗原始檔和標頭檔案
    │  mainwindow.h
    │  myintvalidator.cpp		//QIntValidator的派生類,重寫fixup()
    │  myintvalidator.h
    │  mysetting.json
    │  res.qrc					//資原始檔,新增css、圖片檔案
    │  serialportwidget.cpp		//QWidget的派生類,在其中串列埠的讀寫
    │  serialportwidget.h
    │  serial_port.pro			//工程檔案
    │  serial_port.pro.user
    │  setting.json				//程式自動建立用於儲存各種設定
    │      
    ├─image						//存放圖片
    │      closebtn.png
    │      closebtn2.png
    │      openbtn.png
    |	   logo.ico
    |      windowicon.png
    │      
    └─style						//存放qss/css檔案
            mystyle.css

使用json檔案儲存引數,比如某個核取方塊是否被勾上,是否顯示時間,文字瀏覽器背景色等等,有關json檔案的讀寫,這篇部落格寫的不錯:https://blog.csdn.net/cpp_learner/article/details/118421096

部分程式碼

串列埠助手的核心部分就是序列通訊。

QSerialPort類

QSerialPort提供了一些函式去訪問串列埠。

Provides functions to access serial ports.

獲取串列埠名

QSerialPortInfo類可以獲取已存在串列埠的資訊:串列埠描述、串列埠名、製造商、串列埠序列號等。使用靜態函式QSerialPortInfo::availablePorts()獲取所有的串列埠資訊,再透過foreach遍歷每個串列埠的資訊。

Provides information about existing serial ports.
Use the static functions to generate a list of QSerialPortInfo objects. Each QSerialPortInfo object in the list represents a single serial port and can be queried for the port name, system location, description, and manufacturer. The QSerialPortInfo class can also be used as an input parameter for the setPort() method of the QSerialPort class.

//獲取串列埠資訊
QList<QSerialPortInfo> infos = QSerialPortInfo::availablePorts();
for (const QSerialPortInfo &info : infos)		//foreach遍歷串列埠資訊
    serialPortComboBox->addItem(info.portName());   //獲取串列埠名

從串列埠讀取資料

QSerialPort *serialport = new QSerialPort;
//串列埠引數的設定,具體的值參照QT官方的文件
serialport->setPortName(portName);	//設定串列埠名
serialport->setBaudRate(b);	//設定波特率
serialport->setDataBits(databits);	//設定資料位
serialport->setStopBits(stopbits);	//設定停止位
serialport->setParity(parity);	//設定校驗位

if(!serialport->open(QIODevice::ReadOnly))	//只讀方式開啟檔案失敗
{
    qWarning() << "open serial port error";
    return;
}
QByteArray data = serialport.readAll();	//以位元組的方式讀取資料

向串列埠寫資料

if(!serialport->open(QIODevice::WriteOnly))	//只寫方式開啟檔案失敗
{
    qWarning() << "open serial port error";
    return;
}

QByteArray data("hello");
serialport.write(data);	//向串列埠寫資料,需要先設定相關的引數

關閉串列埠

serialport.close();

專案打包成exe

見另一篇部落格:https://www.cnblogs.com/qianxiaohan/p/18237089

測試結果

使用Virtual Serial Port Driver新增一對虛擬串列埠,COM2 <==> COM3。

QT實現簡易串列埠助手

自制的簡易串列埠助手選擇COM2,另一個串列埠助手選擇COM3,以此來測試自制的簡易串列埠助手。可以看到簡易串列埠助手可以正常地實現資料的收發。

專案地址:https://github.com/qianxiaohan/QTProject/tree/main/serial_port

相關文章