http://blog.sina.com.cn/s/blog_6dd8f2b70101hlo1.html
//对话框程序
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
read_port = new mythread(this);
connect(this->read_port, SIGNAL(read_port_data()), this, SLOT(display_data()));
}
Dialog::~Dialog()
{
//delete this->my_serialport;
delete ui;
}
void Dialog::on_pushButton_clicked()//open serial
{
this->read_port->start();
}
void Dialog::display_data()
{
ui->textBrowser->setText(this->read_port->requestData);
}
//对话框程序.h
#ifndef DIALOG_H
#define DIALOG_H
#include
#include "mythread.h"
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
private slots:
void on_pushButton_clicked();
void display_data();
private:
Ui::Dialog *ui;
mythread *read_port;
};
#endif // DIALOG_H
//关键的串口设置程序,记得要在pro里边加入QT += serialport而且必须在第一和第二的参数位置上
#include "mythread.h"
#include
mythread::mythread(QObject *parent) :
QThread(parent)
{
my_serialport = new QSerialPort(this);
}
void mythread::run()
{
this->my_serialport->setPortName("com3");
this->my_serialport->open(QIODevice::ReadWrite);
this->my_serialport->setBaudRate(115200);
this->my_serialport->setDataBits(QSerialPort::Data8);
this->my_serialport->setParity(QSerialPort::NoParity);
this->my_serialport->setStopBits(QSerialPort::OneStop);
this->my_serialport->setFlowControl(QSerialPort::NoFlowControl);
while(1)
{
requestData = "";
while(this->my_serialport->waitForReadyRead(10))
{
requestData += this->my_serialport->readAll();
}
if(!requestData.isEmpty())
{
emit(this->read_port_data());
qDebug() << "===============" <<requestData;
}
}
}