I have several classes, inherited from a base one. I want to add some functionality, a timer to be exact, and functions to handle it, to all child classes, except one. Cause of that I can't just add this code to parent class. What is the best way to handle this task, avoiding code copying? Thanks!
You can use a mixin, create a class with a timer and other classes that want to use it inherit from it. This class should not inherit form anything if possible.
Edit to add an example:
you create a class without inherit from QObject
:
class TimerMixIn {}
Make any class that needs to use TimerMixIn
inherit from it:
class A : public QObject, public TimerMixIn {}
class B : public QWidget, public TimerMixIn {}
-
How is this the accepted answer. It is unclear and incomplete, to say the least. – scopchanov Oct 24 '20 at 22:44
-
1@scopchanov It's about as clear and complete as the question, I would say :) – cigien Oct 24 '20 at 23:04
-
-
2@scopchanov Agreed. Hard to see how to answer this better with the info in the question. Probably best not to have answered it in the first place :) – cigien Oct 24 '20 at 23:09
-
The fact that you have this issue indicates a problem with your inheritance structure.
You could create a BaseWithTimer
class which all but 1 of your classes inherit from. I.e.:
Base
`- BaseWithTimer
| `- A
| - B
`- C
If you are sure that these classes are best represented in the form of a hierarchy, then you can do one of the following:
Embed QTimer
into the base class:
class BaseWithTimer : public QObject
{
Q_OBJECT
protected:
QTimer m_timer;
};
Do nothing more than just inherit from QObject
:
class AnyClassWhereTimerNeeded : public QObject // no need more than just QObject
{
Q_OBJECT
public:
AnyClassWhereTimerNeeded()
{
// To stop the timer you have to save the id it returns
startTimer(1000);
// But you can start many timers without creation any new objects
startTimer(50);
startTimer(1000);
startTimer(60000);
}
protected:
void timerEvent(QTimerEvent* event) override
{
// do what you need
}
};
As you see, the first approach is based on signals and slots, when the second is event based. As for me, embedding QTimer
is more handy.
The
QTimer
class provides a high-level programming interface with single-shot timers and timer signals instead of events. There is also aQBasicTimer
class that is more lightweight thanQTimer
and less clumsy than using timer IDs directly.
Also do not forget to read https://doc.qt.io/qt-5/timers.html