我知道如何等待单个对象完成,使用
QEventLoop eventLoop;
connect(&obj, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec();
但是现在我有几个我想并行“运行”的对象,所以我需要等到所有对象都发送了它们的 finished()
信号。
这就像 WaitForMultipleObjects WinApi 函数的信号槽版本。
我应该怎么做?
最佳答案
我会将完成的信号连接到一个类,该类计算接收到的信号数量并在达到预期计数时发出 quit()。
像这样:
class EmitIfCountReached : public QObject
{
Q_OBJECT
public:
EmitIfCountReached( int expectedCount, QObject* parent = nullptr) : m_expected(expectedCount), m_count(0), QObject(parent) {}
signals:
void finished();
protected slots:
void increment() {
m_count++;
if (m_count >= m_expected) {
emit finished();
}
}
protected:
int m_count;
int m_expected;
};
关于c++ - 等待多个对象发出信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19789262/