Reputation: 21923
I have 3 classes that inherit from 3 different classes which all inherit from QWidget
base class.
For example:
MyMainWindow : public QMainWindow : public QWidget
MyPushButton : public QPushButton : public QWidget
MyTextEdit : public QTextEdit : public QWidget
And I will have more classes like this eventually.
What I'd like to do now, is add a common method to all my classes; this means it should be added to the QWidget
base class, but I can't edit it (I'd rather not change the Qt source code for one method).
Is this kind of behaviour possible? I've already tried using interfaces like so:
class MyTextEdit : public QTextEdit, IMyMethodContainer { ... };
But the problem is, I need to access QObject::connect(sender, signal, this, slot);
in IMyMethodContainer
, and by this
I'm trying to access the MyTextEdit
, not the IMyMethodContainer
, which is not a subclass of QWidget
.
Upvotes: 1
Views: 116
Reputation: 275585
CRTP might help.
template<typename Derived, typename Base>
struct InjectMethod: Base {
static_assert( std::is_base_of< InjectMethod<Derived,Base>, Derived >::value, "CRTP violation" );
Derived* self() { return static_cast<Derived*>(this); }
Derived const* self() const { return static_cast<Derived*>(this); }
void my_method() {
// use self() inside this method to access your Derived state
}
};
Then:
class MyTextEdit: InjectMethod< MyTextEdit, QTextEdit > {
};
class MyPushButton: InjectMethod< MyPushButton, QPushButton > {
};
inside InjectMethod< MyTextEdit, QTextEdit >
you have access to a self()
pointer that has access to all stuff inside MyTextEdit
, and inside InjectMethod< MyPushButton, QPushButton >
the same.
You may not need the Derived
portion -- possibly having a single template parameter (your base) would be enough, if you only use QWidget
functionality.
Upvotes: 2
Reputation: 245
In Java you can "extend" QWidget and add your custom methods there.
Class MyQWidgetExtension extends QWidget { ... }
Your other classes (QMainWindow, QpushButton, QtextEdit) just extend ("inherit") from that. Is there similar for C++?
Class MyQWidgetExtension : public QWidget { ... }
Upvotes: 0