简体   繁体   中英

Override Qt slot in subclass

I have a base class, which defines a Qt slot

class Base
{
public:
    Base()
    {
        connect(otherobject, SIGNAL(mySignal), this, SLOT(mySlot));
    }
public slots:
    virtual void mySlot()
    {}
}

Subclass A just implements some other stuff. Subclass B overrides the slot

class SubB : Base
{
public:
    SubB() : Base() 
    {
        // Necessary?
        connect(otherobject, SIGNAL(mySignal), this, SLOT(mySlot));
    }
public slots:
    virtual void mySlot() override
    {}
}

Does the override of the slot also replace the connection, which was done before in the Bass constructor (Ie The connect in SubB would be unnecessary)?

It gets better: you don't need any special treatment for the slot in the derived class. There's no need to make it virtual (it already is per C++ semantics), and there's no need to make it a slot again (it already is per Qt semantics). It is incorrect to add the second connection in Derived , it'll simply result in the slot being activated twice per every activation of the signal.

Remember that signals and slots are regular C++ methods, and that slots are invoked from machine-generated code that looks exactly as if you called the slot without specifying the particular class it should be in. Thus a virtual slot acts as you think it should, given the semantics of C++.

The below is sufficient:

class Base : public QObject
{
  Q_OBJECT
public:
  Base(QObject * src, QObject * parent = 0) : QObject(parent)
  { connect(src, SIGNAL(mySignal), SLOT(mySlot)); }
  Q_SLOT virtual void mySlot() {}
};

class Derived : public Base
{
  Q_OBJECT
public:
  Derived(QObject * src, QObject * parent = 0) : Base(src, parent) {}
  void mySlot() Q_DECL_OVERRIDE { ... }
};

You don't need to put the same connect in the subclass constructor. When a SubB object is created, the connect in the Base constructor will connect the right slot (the one overridden in SubB).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM