Keith Bourdon
Keith Bourdon

Reputation: 1

QtConcurrent::run with a virtual class member

So I'm trying to encapsulate a timer class which will handle all of the gory details of multi-threading and timers.

Here's my code: 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());
}

The idea was TimedEvent would be a base class and I would be able to create derived classes very easily.

class MyClass : public TimedEvent
{
    public:
    MyClass( const int timeoutInMsecs );
    TimeoutWorkProcedure(){ do some background stuff };
};

The problem is I cannot figure out what to pass to the QtConcurrent::run call. Not sure this is even possible. I could move the QTConcurrent::run call to the derived class, but I anticipate there being several of these derived classes.

Any ideas would be appreciated.

K.

Upvotes: 0

Views: 333

Answers (1)

ixSci
ixSci

Reputation: 13698

This code:

void TimedEvent::TimeoutWorkThread()
{
    QtConcurrent::run(this, &TimedEvent::TimeoutWorkProcedure);
}

is perfectly fine and will do what you expect. It will call an overridden version of TimeoutWorkProcedure.

Upvotes: 1

Related Questions