btnserialthread.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "btnserialthread.h"
  2. BtnSerialThread::BtnSerialThread(QObject *parent) : QThread(parent)
  3. {
  4. btnSerialTool = nullptr;
  5. connect(this, &BtnSerialThread::destroySerialTool, this, &BtnSerialThread::onDestroySerialTool, Qt::QueuedConnection);
  6. }
  7. BtnSerialThread::~BtnSerialThread()
  8. { qDebug() << "SerialToolThread:" ;
  9. // emit destroySerialTool();
  10. // // if (isRunning()) {
  11. // // qDebug() << "SerialToolT:" ;
  12. // // quit();
  13. // // wait();
  14. // // }
  15. qDebug() << "Current thread in run():" << QThread::currentThread();
  16. qDebug() << "SerialToolThread object is in thread:" << this->thread();
  17. qDebug() << "SerialTool object is in thread:" << btnSerialTool->thread();
  18. }
  19. void BtnSerialThread::run()
  20. {
  21. btnSerialTool = new BtnSerialTool();
  22. emit serialToolCreated();
  23. qDebug() << "SerialToolThread object is in thread:" << this->thread();
  24. qDebug() << "SerialTool object is in thread:" << btnSerialTool->thread();
  25. qDebug() << "Current thread in run():" << QThread::currentThread();
  26. // 连接信号
  27. connect(this, &BtnSerialThread::sendDataRequest, btnSerialTool, &BtnSerialTool::handleSendDataReques, Qt::QueuedConnection);
  28. connect(btnSerialTool, &BtnSerialTool::dataReceived, this, &BtnSerialThread::handleReceivedData, Qt::QueuedConnection);
  29. // 启动事件循环
  30. exec();
  31. }
  32. // 处理接收到的数据
  33. void BtnSerialThread::handleReceivedData(const QByteArray &data)
  34. {
  35. // 这里可以添加具体的处理逻辑,例如打印接收到的数据
  36. qDebug() << "Received data:" << data;
  37. // 可以将接收到的数据通过信号发送出去
  38. emit dataReceived(data);
  39. }
  40. void BtnSerialThread::onDestroySerialTool()
  41. {
  42. qDebug() << "触发信号" ;
  43. if (btnSerialTool) {
  44. qDebug() << "delete serialTool";
  45. delete btnSerialTool;
  46. btnSerialTool = nullptr;
  47. }
  48. }