我正在尝试做一个项目,正在使用Qt GUI C ++ 5.6.2在窗口上创建一些图形。
我有两种名为“ createVerticalSpeedIndicator”和“ createAirSpeedIndicator”的方法。这些方法需要使用while(1)循环创建一些图形,并使用qApp-> processEvents();。在一个窗口上,并且当其中一个正在工作而另一个处于不活动状态时,它们则表现出色。但是我需要同时并始终同时运行它们。

我该怎么做才能同时始终运行它们。

非常感谢

最佳答案

解决方案是反转控制流。 while() { ... processEvents() ... }是异步代码中的反模式,因为它假定您拥有控制源,而您实际上没有。您很幸运,没有用完堆栈,因为processEvents可能会重新输入createXxx方法。

这是一个完整的转换示例:

// Input
void Class::createVerticalSpeedIndicator() {
  for (int i = 0; i < 100; i ++) {
    doStep(i);
    QCoreApplication::processEvents();
  }
}




// Step 1 - factor out state
void Class::createVerticalSpeedIndicator() {
  int i = 0;
  while (i < 100) {
    doStep(i);
    QCoreApplication::processEvents();
    i++;
  }
};




// Step 2 - convert to continuation form
void Class::createVerticalSpeedIndicator() {
  int i = 0;
  auto continuation = [=]() mutable {
    if (!(i < 100))
      return false;
    doStep(i);
    QCoreApplication::processEvents();
    i++;
    return true;
  };
  while (continuation());
};




// Step 3 - execute the continuation asynchronously
auto Class::createVerticalSpeedIndicator() {
  int i = 0;
  return async(this, [=]() mutable {
    if (!(i < 100))
      return false;
    doStep(i);
    i++; // note the removal of processEvents here
    return true;
  });
};

template <typename F> void async(QObject * parent, F && continuation) {
  auto timer = new QTimer(parent);
  timer->start(0);
  connect(timer, &QTimer::timeout, [timer, c = std::move(continuation)]{
    if (!c())
      timer->deleteLater();
  });
}


那时,您可以对createAirSpeedIndicator应用相同的转换,并在类的构造函数中启动它们:

Class::Class(QWidget * parent) : QWidget(parent) {
  ...
  createVerticalSpeedIndicator();
  createAirSpeedIndicator();
}


这两个任务将在主线程中异步和伪并发运行,即每个任务将交替执行一个步骤。

假设我们要链接任务,即仅在前一个任务完成后才开始任务。用户代码中的修改可以很简单:

Class::Class(QWidget * parent) : QWidget(parent) {
  ...
  createVerticalSpeedIndicator()
  >> createAirSpeedIndicator()
  >> someOtherTask();
}


async函数现在必须返回一个允许进行此类连接的类:

struct TaskTimer {
  QTimer * timer;
  TaskTimer & operator>>(const TaskTimer & next) {
    next.timer->stop();
    connect(timer, &QObject::destroyed, next.timer, [timer = next.timer]{
      timer->start(0);
    });
    timer = next.timer;
    return *this;
  }
};

template <typename F> TaskTimer async(QObject * parent, F && continuation) {
  TaskTimer task{new QTimer(parent)};
  task.timer->start(0);
  connect(task.timer, &QTimer::timeout,
          [timer = task.timer, c = std::move(continuation)]{
            if (!c())
              timer->deleteLater();
  });
  return task;
}

08-19 22:37