最近需要写一个串口工具,一开始完全找不到方向只好到处瞎碰,写这个就是希望后来者不要那么心累的到处瞎找....
首先得把这个第三方库下载下来,链接:http://code.google.com/p/qextserialport/downloads/detail?name=qextserialport-1.2rc.zip
下载好了之后,解压,在红色框里的文件夹里把对应的.cpp和.h文件拷到你创建的文件夹下(什么系统就拷什么后缀的)。
在.pro里添加:
include(qextserialport.pri)
然后可以看到如下框架:
首先我是先做的界面,如图:(直接拉的框框,不是敲代码实现的,见谅见谅)
那5个Btn直接右键转到槽选择第一个信号clicked()之后会跳到tool.cpp,大的框是textBrowser小的是lineEdit。
头文件tool.h:
#ifndef TOOL_H
#define TOOL_H
#include <QMainWindow>
#include <QWidget>
#include <QTimer>
#include <QIODevice>
#include "qextserialport.h"
#include "qextserialenumerator.h"
namespace Ui {
class tool;
}
class tool : public QMainWindow
{
Q_OBJECT
public:
explicit tool(QWidget *parent = 0);
~tool();
private:
Ui::tool *ui;
QextSerialPort *myCom;
private:
void initPortList();
private slots:
void readMyCom();
void on_openMyComBtn_clicked();
void on_closeMyComBtn_clicked();
void on_cleanReceBtn_clicked();
void on_sendDataBtn_clicked();
void on_cleanSendBtn_clicked();
void on_textBrowser_textChanged();
};
#endif // TOOL_H
tool.cpp文件:
#include "tool.h"
#include "ui_tool.h"
#include <QtCore>
#include <QDate>
tool::tool(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::tool)
{
ui->setupUi(this);
//设置各按钮初始状态
ui->closeMyComBtn->setEnabled(false);
ui->cleanReceBtn->setEnabled(false);
ui->cleanSendBtn->setEnabled(false);
ui->sendDataBtn->setEnabled(false);
initPortL