main.cpp
#include <QtWidgets/QApplication>
#include <QtCore/QDebug>
#include "MyClass.h"
void MyClass::recvData(void)
{
if (serial->bytesAvailable())
{
const QByteArray dat = serial->readAll();
qDebug() << "已接收:" << QString::fromUtf8(dat);
}
}
void MyClass::start(void)
{
serial = new QSerialPort();
connect(serial, QSerialPort::readyRead, this, recvData);
serial->setPortName("COM36");
serial->setBaudRate(115200);
if (serial->open(QIODevice::ReadWrite))
qDebug() << "serial open OK ";
else
qDebug() << "serial open ERROR ";
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyClass m;
m.start();
return app.exec();
}
MyClass.h
#pragma once
#include <QtCore/QObject>
#include <QtSerialPort/QSerialPort>
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass() {}
void start(void);
public slots:
void recvData(void);
private:
QSerialPort *serial;
};
demo.pro
QT += core widgets serialport
TARGET = qtdemo
SOURCES += main.cpp
CONFIG += console
HEADERS += MyClass.h
serialport 须通过 QApplication exec 运行, 否则槽函数无法响应。故 widgets 也是必须;
编译运行
mkdir build && cd build
qmake .. && make
网友评论