Sometimes, when writing connect, you may hesitate to ask the question-do not need to be a virtual function in my slot function. I will ask myself this question every time I write connect, because if you don't go into MOC, you won't find too many problems.
For example, there is a demo.
#include <QApplication>#include <QObject>#include <QDebug>class Test : public QObject{ Q_OBJECTpublic: void onEmit() { emit test(); }signals: void test();};class Base : public QObject{ Q_OBJECTpublic: Base(Test *p) { this->p = p; connect(p,SIGNAL(test()), this, SLOT(onTest())); } void testConnect() { // connect(p,SIGNAL(test()), this, SLOT(onTest())); }private slots: void onTest() { qDebug() << "This is Base‘s test"; }private: Test *p;};class Child : public Base{ Q_OBJECTpublic: Child(Test *p) : Base(p) { }private slots: void onTest() { qDebug() << "This is Child‘s test"; }};int main(int argc, char **argv){ Test t; Base *b = new Child(&t); b->testConnect(); t.onEmit(); return 0;}#include "main.moc"
In short, many people will habitually establish the connect mechanism when constructing functions of the base class, but at this time, because one of Objective C ++ does not recommend using virtual functions in constructor and analytics functions, it is clear that in the base, if you do not call another testconnect, it is written directly in the constructor. At this time, although the address of this in connect is the same as that of child, if you use typeid, you can find that when the base constructor is used when the child is created,Connect's this type is base,At this point, the MOC file will choose to use base: metaobject instead of using child: metaobject to associate with the test signal. What will happen at this time? Yes, the base class Pointer Points to the subclass type. Even if your slot function does not implement a virtual function, you think connect will call the slot function of your subclass, but the actual situation is, the base class pointer still calls the base class function. Therefore, you must set the slot function to a virtual function when writing connect in the constructor.
Of course, you can also connect without the constructor. functions such as testconnect are connected after the object is constructed. At this time, metaobject will select the correct type you have created, at this time, no matter whether you are virtual or not, the slot function will call the type actually pointed to (including the subclass, or the base class pointer pointing to the subclass, will call the slot function of the subclass), so pay attention to the connect in the constructor.