Qt's 'connect()' and virtual slot function
-
See the code below:
class Base : public QObject { Q_OBJECT public: Base(QObject *p = nullptr) : QObject(p) { } void initb() { connect(this, &Base::sig, this, &Base::slot1, Qt::UniqueConnection); } signals: void sig(); public slots: virtual void slot1() { // blabla.... qDebug() << "base"; } }; class Derived : public Base { Q_OBJECT public: Derived(QObject *p = nullptr) : Base(p) { } void initd() { Base::initb(); } void sig_emit() { emit sig(); } public slots: virtual void slot1() { // blabla qDebug() << "derived"; } }; int main(int argc, char *argv[]) { Derived derived; derived.initd(); derived.sig_emit(); }
It will output "derived", that is, the base class's connect option, connect the signal to the derived class's slot. But apparently the arguments I passed to the connect function is the base class's 'this' pointer and the base class's 'slot1()' function pointer. It's a bit confused to me. Can someone explain it more?
-
Well you didn't really instantiate a
Base
object. So thethis
pointer is a Derived object. You are callingBase::initb()
inside of your Derived object. So when it gets to the connect call insideinitb
the this pointer will be the one pointing at the derived object.Also since you derived your
slot1()
function as a virtual then Base::slot1 that is passed to the connect will point to the derived function.