btnserialthread.cpp 1.9 KB

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