简体   繁体   English

如何将 boost::asio::deadline_timer 与 Qt 一起使用?

[英]How to use boost::asio::deadline_timer with Qt?

How could using boost::asio::deadline_timer with Qt?如何将boost::asio::deadline_timer与 Qt 一起使用? I am new to Boost C++ library and try documentation examples in separate project and it work.我是 Boost C++ 库的新手,并在单独的项目中尝试文档示例,它可以工作。 But i could not using it in my project which use Qt for GUI.但我无法在我的项目中使用它,它使用 Qt 作为 GUI。

Note:笔记:

  • I Need a long interval and QTimer could not work with a long interval.我需要很长的时间间隔,而QTimer不能以很长的时间间隔工作。

Based on an answer to your previous question it's very easy to implement your own deadline timer using Qt only (that seems to be what you'd prefer)...根据对您之前问题的回答,仅使用 Qt 来实现您自己的截止日期计时器非常容易(这似乎是您更喜欢的)......

class deadline_timer: public QObject {
  using super = QObject;
  Q_OBJECT;
public:
  using deadline_id = uint_least64_t;
signals:
  void timeout(deadline_id, QDateTime) const;
public:
  explicit deadline_timer (int resolution_milliseconds = 1000, QObject *parent = nullptr)
    : super(parent)
    {
      m_timer.setInterval(resolution_milliseconds);
      QObject::connect(&m_timer, &QTimer::timeout, this, &deadline_timer::handle_timeout);
    }

  /*
   * Adds a new deadline and returns associated id.  When the deadline is
   * reached the timeout signal will be emitted with the corresponding id
   * and time.
   */
  deadline_id start (const QDateTime &deadline)
    {
      m_deadlines[deadline].insert(++s_id);
      if (!m_timer.isActive()) {
        m_timer.start();
      }
      return s_id;
    }
  void stop ()
    {
      m_timer.stop();
    }
private:
  void handle_timeout ()
    {
      auto now = QDateTime::currentDateTime();
      for (auto i = m_deadlines.begin(); i != m_deadlines.end() && now >= i->first; i = m_deadlines.begin()) {
        for (const auto &j: i->second) {
          emit timeout(j, i->first);
        }
        m_deadlines.erase(i);
      }
      if (m_deadlines.empty()) {
        m_timer.stop();
      }
    }
  static deadline_id                         s_id;
  QTimer                                     m_timer;
  std::map<QDateTime, std::set<deadline_id>> m_deadlines;
};

deadline_timer::deadline_id deadline_timer::s_id = 0;

The use as...用作...

deadline_timer dt;
QObject::connect(&dt, &deadline_timer::timeout,
                 [](deadline_timer::deadline_id id, QDateTime deadline)
                   {
                     std::cout << "\ndeadline " << id << " passed\n";
                 });
auto id = dt.start(QDateTime::currentDateTime().addYears(1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM