Mahi
Mahi

Reputation: 21923

Add functionality to class and all of it's subclasses

I have 3 classes that inherit from 3 different classes which all inherit from QWidget base class. For example:

  1. MyMainWindow : public QMainWindow : public QWidget
  2. MyPushButton : public QPushButton : public QWidget
  3. 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

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

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

mjash
mjash

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

Related Questions