Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual Qt signal?

Tags:

c++

qt

Whilst reviewing some Qt C++ code I came across this:

class Foo
{
  Q_OBJECT

signals:
  virtual void someSignal(const QString& str, int n)
  {
    Q_UNUSED(str);
    Q_UNUSED(n);
  }
  ...
};

Now, Qt signals cannot have a body so I'm surprised this even compiles (perhaps because the body is effectively empty). I also don't see the point of making a signal virtual as ... it can't have a body so how can it be overridden?

Am I missing something here or is this a valid code smell?

like image 751
Rob Avatar asked Sep 08 '10 12:09

Rob


People also ask

Can Qt slots be virtual?

Yes, just like regular c++ pure virtual methods.

How do I create a Qt signal?

In Qt, we have an alternative to the callback technique: We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal.

How do Qt signals work?

The Qt signals/slots and property system are based on the ability to introspect the objects at runtime. Introspection means being able to list the methods and properties of an object and have all kinds of information about them such as the type of their arguments.

How do I connect my signal to my slot Qt?

To connect the signal to the slot, we use QObject::connect(). There are several ways to connect signal and slots. The first is to use function pointers: connect(sender, &QObject::destroyed, this, &MyObject::objectDestroyed);


1 Answers

That looks smelly to me.

It's valid to declare a signal in a base class and then emit it from a derived class, e.g.

class MyBase : public QObject
{
    Q_OBJECT
// ...
signals:
    void somethingHappened();
};

class MyDerived : public MyBase
{
    Q_OBJECT
// ...
    void doSomething();
};

void MyDerived::doSomething()
{
    // ....
    emit somethingHappened();
}

Maybe that's what the declaration in the question was meant to achieve.

like image 63
Gareth Stockwell Avatar answered Sep 22 '22 17:09

Gareth Stockwell