所以我试图封装一个计时器类,它将处理多线程和计时器的所有细节。
这是我的代码: TimedEvent.h
class TimedEvent : public QObject
{
Q_OBJECT
public:
explicit TimedEvent(QObject *parent = 0);
TimedEvent(const int intervalInMsecs);
virtual void TimeoutWorkProcedure() = 0;
private slots:
void TimeoutWorkThread();
protected:
QTimer *myTimer;
};
TimedEvent.cpp
TimedEvent::TimedEvent(QObject *parent) :
QObject(parent)
{
}
TimedEvent::TimedEvent(const int intervalInMsecs)
{
// Create timer
//
myTimer = new QTimer(this);
// Connect the timeout signal to our virtual callback function
//
connect(myTimer, SIGNAL(timeout()), this, SLOT(TimeoutWorkThread()));
myTimer->start(intervalInMsecs);
}
void TimedEvent::TimeoutWorkThread()
{
QtConcurrent::run(this, &TimedEvent::TimeoutWorkProcedure());
}
想法是TimedEvent将是一个基类,我将能够非常容易地创建派生类。
class MyClass : public TimedEvent
{
public:
MyClass( const int timeoutInMsecs );
TimeoutWorkProcedure(){ do some background stuff };
};
问题是我无法弄清楚要传递给QtConcurrent :: run调用的内容。不确定这是否可行。我可以将QTConcurrent :: run调用移动到派生类,但我预计会有几个派生类。
任何想法都会受到赞赏。
ķ。
答案 0 :(得分:1)
此代码:
void TimedEvent::TimeoutWorkThread()
{
QtConcurrent::run(this, &TimedEvent::TimeoutWorkProcedure);
}
完全没问题,会做你期望的事。它将调用TimeoutWorkProcedure
的重写版本。