文章目录
- 文章介绍
- code
- main.cpp
- SerialPort.qml
- SerialPortHandler.h
文章介绍
案例MF改为单例模式
参考之前写过的关于单例模式的文章单例模式1、单例模式2
code
main.cpp
qmlRegisterSingletonType(“com.example.serialport”, 1, 0, “SerialPortHandler”, SerialPortHandlerGetInstance);
SerialPort.qml
- 导入模块
- 调用SerialPortHandler类
SerialPortHandler.h
#ifndef SERIALPORTHANDLER_H
#define SERIALPORTHANDLER_H#include <QObject>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QQmlEngine>
#include <QJSEngine>class SerialPortHandler : public QObject
{Q_OBJECTQ_PROPERTY(bool isSerialPortOpen READ isSerialPortOpen NOTIFY serialPortOpenChanged)public:// 获取单例实例static SerialPortHandler* getInstance() {static SerialPortHandler instance; // 确保只有一个实例return &instance;}explicit SerialPortHandler(QObject *parent = nullptr);~SerialPortHandler(); // 析构函数Q_INVOKABLE void openSerialPort(const QString &portName); // 打开指定串口Q_INVOKABLE void closeSerialPort(); // 关闭串口Q_INVOKABLE QStringList getAvailablePorts() const; // 获取可用串口列表bool isSerialPortOpen() const; // 检查串口是否打开signals:void serialPortOpened(); // 串口打开信号void serialPortOpenChanged(); // 串口状态改变信号void dataReceived(const QString &data); // 数据接收信号private slots:void readData(); // 读取数据槽函数public slots:void sendData(const QString &data); // 发送数据槽函数private:QSerialPort serialPort; // 串口对象bool m_isSerialPortOpen; // 串口打开状态// 禁用拷贝构造函数和赋值操作符Q_DISABLE_COPY(SerialPortHandler)
};// 单例获取函数声明
static QObject* SerialPortHandlerGetInstance(QQmlEngine *engine, QJSEngine *scriptEngine) {Q_UNUSED(engine)Q_UNUSED(scriptEngine)return SerialPortHandler::getInstance();
}#endif // SERIALPORTHANDLER_H