messagequeue.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "messagequeue.h"
  2. #include "qdebug.h"
  3. #include <QApplication>
  4. #include <QMessageBox>
  5. static bool isNumeric(const QVariant &variant)
  6. {
  7. int type = variant.type();
  8. return (type == QMetaType::Int || type == QMetaType::UInt || type == QMetaType::Double
  9. || type == QMetaType::Float || type == QMetaType::Long || type == QMetaType::ULong
  10. || type == QMetaType::LongLong || type == QMetaType::ULongLong);
  11. }
  12. void MessageQueue::processQueue()
  13. {
  14. if (isProcessing || messageQueue.isEmpty()) {
  15. return;
  16. }
  17. isProcessing = true;
  18. QString currentMessage = messageQueue.dequeue();
  19. QVariant messageBoxPointX = this->messageBoxPointX;
  20. QVariant messageBoxPointY = this->messageBoxPointY;
  21. QVariant messageTitle = this->messageTitle;
  22. qDebug() << "currentMessage" << currentMessage << messageBoxPointX << messageBoxPointY
  23. << messageTitle;
  24. // 在主线程中显示消息框
  25. QMetaObject::invokeMethod(
  26. QApplication::instance(),
  27. [this, currentMessage, messageBoxPointX, messageBoxPointY, messageTitle]() {
  28. bool isokX = false;
  29. bool isokY = false;
  30. int x = messageBoxPointX.toInt(&isokX);
  31. int y = messageBoxPointY.toInt(&isokY);
  32. qDebug() << x << y << isokX << isokY;
  33. QMessageBox *messageBox = new QMessageBox;
  34. if (isokX && isokY && isNumeric(messageBoxPointX) && isNumeric(messageBoxPointY)) {
  35. messageBox->move(x, y);
  36. }
  37. QString title = messageTitle.toString();
  38. if (title.isEmpty()) {
  39. title = tr("Tips");
  40. }
  41. messageBox->setWindowModality(Qt::NonModal);
  42. messageBox->setText(currentMessage);
  43. messageBox->setWindowTitle(title);
  44. connect(messageBox, &QMessageBox::finished, this, &MessageQueue::onMessageBoxClosed);
  45. messageBox->show();
  46. },
  47. Qt::QueuedConnection);
  48. }