Multiple inheritance of QObject is not supported, check this post.
Here's a little example what can be done with QMetaObject.
Let's take a look at a classical C++ interface approach first. Here we define an interface:
class SomeInterface
{
public:
virtual ~SomeInterface() {}
virtual void operation() = 0;
};
class SomeInterface
{
public:
virtual ~SomeInterface() {}
virtual void operation() = 0;
};
To copy to clipboard, switch view to plain text mode
And then implement the interface in various classes:
class SomeWidget
: public QWidget,
public SomeInterface
{
public:
// SomeInterface
void operation();
};
class SomeObject
: public QObject,
public SomeInterface
{
public:
// SomeInterface
void operation();
};
class SomeWidget : public QWidget, public SomeInterface
{
public:
SomeWidget(QWidget* parent = 0);
// SomeInterface
void operation();
};
class SomeObject : public QObject, public SomeInterface
{
public:
SomeObject(QWidget* parent = 0);
// SomeInterface
void operation();
};
To copy to clipboard, switch view to plain text mode
Ok, so far so good. Then we have a plain QObject pointer in hand which we need then cast to the appropriate type to be able to call SomeInterface methods:
// QObject* object
SomeInterface* some = dynamic_cast<SomeInterface*>(object);
if (some)
{
some->operation();
}
// QObject* object
SomeInterface* some = dynamic_cast<SomeInterface*>(object);
if (some)
{
some->operation();
}
To copy to clipboard, switch view to plain text mode
Not very handy is it? Well, Qt at least has a more convenient way for solving such..
We can get away without defining any interface at all by declaring all the functions we had in the interface as slots:
{
Q_OBJECT
public:
public slots:
// no more "SomeInterface", just slots
void operation();
};
class SomeWidget : public QWidget
{
Q_OBJECT
public:
SomeWidget(QWidget* parent = 0);
public slots:
// no more "SomeInterface", just slots
void operation();
};
To copy to clipboard, switch view to plain text mode
And then we can simply call the methods through QMetaObject:
// QObject* object
bool ok
= QMetaObject::invokeMethod(object,
"operation");
// QObject* object
bool ok = QMetaObject::invokeMethod(object, "operation");
To copy to clipboard, switch view to plain text mode
QMetaObject::invokeMethod() even supports return value and arguments.. Not bad huh?
Thanks bhughes @ #qt @ freenode!
Bookmarks