[Qt-interest] Basic question on applying QObject principles toInterfaces

Ben Swerts benswerts at telenet.be
Tue May 4 20:17:56 CEST 2010


Hi Mandeep,

There's a way to keep your interface pure virtual without inheriting from
QObject. Signals and slots don't even need to be defined as such in such an
interface. They can be defined as regular pure virtual functions (well, in
fact they don't even have to be defined at all but how would you let your
users know they're available?). In order to be able to call connect, I
provide an object function that returns the QObject pointer.

> Hi All,
> 
> I had a basic doubt on using QObject's in some scenario's. I'll use a
> sample class to illustrate the usage scenario:
> 
> class MyInterface : public QObject
> {
>     Q_OBJECT
> public:
>     virtual ~MyInterface() {}
>     virtual void someMethod() = 0;
> signals:
>     void mySignal();
> };

Can be changed into:

class MyInterface
{
public:
  virtual ~MyInterface() {} = 0;
  virtual const QObject* object() const = 0;
  virtual void someMethod() = 0;
  virtual void mySignal() = 0; // optional
};

> class MyInterfaceImpl : public MyInterface
> {
>     Q_OBJECT
> public:
>     MyInterfaceImpl() {}
>     ~MyInterfaceImpl() {}
> 
>     void someMethod() {
>         // do something
>         emit mySignal();
>     }
> signals:
>     void mySignal();
> }

Can be changed into:

class MyInterfaceImpl : public QObject, public MyInterface
{
  Q_OBJECT
public:
  MyInterfaceImpl() {};
  ~MyInterfaceImpl() {};
  const QObject* object() const { return this; };
  void someMethod() { emit mySignal(); };
signals:
  void mySignal();
};

With this scenario you could also pass in a parent QObject*:

  MyInterfaceImpl(QObject* parent) : QObject(parent) {};

Connects should be done using MyInterface::object() instead of MyInterface.

Hope it helps.
Greets,


	Ben




More information about the Qt-interest-old mailing list