如何使用 CPP 在 qt 中将 QTimer 作为空闲计时器

How to make a QTimer as Idle timer in qt using CPP

我是Qt编程的新手,我想把定时器做成空闲定时器。 问题是只设置 timer->start(0) 是否会使定时器成为空闲定时器? 我怎么知道它是一个空闲计时器。

我想重复 的担忧:

On a general-purpose/multitasking OS (such as Qt usually runs under) you want to minimize your app's CPU usage so that any other programs that may be running can use those leftover CPU cycles (or in the case of a battery-powered device, so that the battery can be conserved). An app that is constantly using CPU cycles while idle would be considered buggy.

timeout为0的应用程序永久占用(多于)一个核心,导致高币耗。


我们开始:QTimer,间隔为 0:

#include <QtWidgets>

// main application

int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup GUI
  QWidget qWinMain;
  qWinMain.setWindowTitle("QTimer - timeout 0");
  QVBoxLayout qVBox;
  QLabel qLblText("Attention!\nThis may cause ventilation noise.");
  qVBox.addWidget(&qLblText);
  QLabel qLblI;
  qVBox.addWidget(&qLblI);
  qWinMain.setLayout(&qVBox);
  qWinMain.show();
  QTimer qTimer;
  qTimer.setInterval(0);
  ushort i = 0;
  // install signal handlers
  QObject::connect(&qTimer, &QTimer::timeout,
    [&]() {
      ++i;
      if (i) qLblI.setText(QString("i: %1").arg(i));
      else app.quit();
    });
  // runtime loop
  qTimer.start();
  return app.exec();
}

输出:

间隔 0 使计时器立即到期。这意味着超时事件附加到事件队列。

因此,我希望队列永久充满超时和绘制事件(用于 qLblI 的更新),直到应用程序退出。


我以前(在开始使用Qt之前)曾经使用过这样的空闲事件。我打算将 UI 事件循环与来自不同来源的轮询“事件”结合起来(并且不知道更好的选择)。因此,轮询函数为自己提供了一个 time-out 选项。因此,轮询函数的调用暂停了进程,直到有事件进入或达到超时。最复杂的事情是以某种方式实现负载平衡,因为我试图在 UI 和其他事件源的处理之间平均分配可用时间。 (这对于 UI 事件与其他事件源同时以高频率接近的情况很重要。)

但是,我怀疑在 Qt 中是否仍然需要这样的摆弄。对于这样的并发,有更好的选择,例如运行 单独线程中的阻塞函数。