耗时IO对象移到子线程,防止UI卡顿

调用QObject::moveToThread,把m_SerialPort的 "线程归属" 从主线程改为m_serialThread;

此后m_SerialPort的所有槽函数(如果连接了信号)都会在m_serialThread中执行,而非主线程;

注意:移线程的前提是m_SerialPort无父对象(如果有父对象,moveToThread会失效),这也是代码中new QSerialPort()不指定父对象的原因。

cpp 复制代码
Q_DECLARE_METATYPE(CheckInfoList)
CommSerialPort::CommSerialPort()
{
    m_SerialPort = new QSerialPort();//不指定父对象
    //注册自定义元类型(跨线程信号槽传递数据用)
    qRegisterMetaType<QList<std::pair<int, int>>>("QList<std::pair<int,int>>");
    qRegisterMetaType<CheckInfoList>("QList<std::pair<int,int>>");

    // 创建工作线程
    m_serialThread = new QThread();
    // 注意:不要连接 finished 到 deleteLater,因为我们在析构函数中手动管理线程生命周期
    
    // 只将串口对象移到工作线程(不要移动 this)
    m_SerialPort->moveToThread(m_serialThread);
    m_serialThread->start();
    
    // 初始化发送时间记录器
    m_lastSendTime.start();

    // 自动重连:定时器在主线程中(因为 this 在主线程)
    m_reconnectTimer = new QTimer(this);
    m_reconnectTimer->setInterval(m_reconnectIntervalMs);
    connect(m_reconnectTimer, &QTimer::timeout, this, &CommSerialPort::onReconnectTimeout);
    
    // 串口错误信号连接(跨线程连接,使用 Qt::QueuedConnection)
    connect(m_SerialPort, &QSerialPort::errorOccurred, this, &CommSerialPort::onErrorOccurred, Qt::QueuedConnection);
    connect(m_SerialPort, &QSerialPort::errorOccurred, this, &CommSerialPort::handleSerialTimeout, Qt::QueuedConnection);

    // m_sendTimer = new QTimer(this);
    // m_sendTimer->setInterval(m_sendIntervalMs);
    // connect(m_sendTimer, &QTimer::timeout, this, &CommSerialPort::SendBufferData);
    // m_sendTimer->start();

    m_commAlertManager = new AlertDialogManager();
}

qt官方:QTimer is a subclass of QObject and as such, it must live in the thread where it was created. It is not safe to access a QTimer from another thread. (QTimer是QObject子类,必须归属创建它的线程;从其他线程访问QTimer是不安全的)

m_reconnectTimer自动重连定时器的onReconnectTimeout重连逻辑已经通过connect将m_reconnectTimer和CommSerialPort绑定了 ,如果后续出现串口错误信号连接没有使用QueuedConnection,会让导致不在同一个线程访问QTimer ,qt没有对访问不同线程中的QTimer设置线程安全 ,可能会导致定时器定时不准,导致后续定时器可能失效

Qt 对这种跨线程操作QTimer的行为不做线程安全保护:

轻量问题:定时器定时不准、启动 / 停止指令无响应(比如调用stop()但定时器还在跑);

严重问题:主线程和子线程同时操作定时器的内部状态,引发内存竞态,程序崩溃。

相关推荐
Behaviour14 小时前
Unity UI循环列表UIScrollViewContent实现
ui·unity·c#·游戏引擎
小小龙学IT20 小时前
Dear ImGui 开源即时模式 GUI 库深度解析
c++·ui·开源
xy345321 小时前
Axure9.0让条形图实现动态交互(鼠标悬停高亮 + 显示详情卡片)
ui·产品经理·原型·axure9.0
mqiqe2 天前
AgentScope Java 2.0 协议集成全景解析:A2A、AG-UI、Agent Protocol 三大开放协议实战指南
java·开发语言·ui
qq_426003962 天前
【UI自动化测试】UI自动化报错解决方案
运维·ui·自动化
Oll Correct2 天前
Adobe illustrator 案例九:百宝箱图标绘制
笔记·ui·adobe·illustrator
xy34532 天前
Axure 9.0 条形图绘制超详细教程:静态展示
ui·产品经理·axure·条形图
LabVIEW开发2 天前
LabVIEW图标编辑器文字模糊现象
ui·编辑器·labview·labview知识·labview功能·labview程序
兰亭妙微UI设计公司3 天前
兰亭妙微B端界面设计分享:Vantary海事无人系统任务平台UI/UX设计解析
ui·ux
伊玛目的门徒3 天前
deepseek harness DSH 安装皮肤脚手架(dsh‑client‑ui‑skin‑center)踩坑完整记录
ui·插件·皮肤·harness·dsh