简体   繁体   中英

Cannot connect QPushButton

If I try to connect a button with a slot, the compiler told me:

QObject::connect: No such slot ClassA::..

ClassB inherit of ClassA. In ClassB I create a button and I will connecting it to a function in ClassB.

connect(btn, SIGNAL(clicked()), this, SLOT(helloWorld()));

The reason is, this is mean ClassA. How can i told the compiler, dont search for helloWorld() in ClassA and use the function helloWorld() in ClassB?

//header of classa
class ClassA : public QDialog
{
 Q_OBJECT
 public:
    ClassA(QObject *parent = 0);
};

//header of classb
class ClassB : public ClassA
{
 public:
   ClassB();

 public slots:
    void helloWorld();
};

//cpp of classa
ClassA::ClassA(QObject *parent)
{
}

//cpp of classb
ClassB::ClassB()
{
QPushButton *btn = new QPushButton("Click");
connect(btn, SIGNAL(clicked()), this, SLOT(helloWorld()));
QHBoxLayout *l = new QHBoxLayout();
l->addWidget(btn);
setLayout(l);
}

void ClassB::helloWorld()
{
   qDebug() << "hello world";
}

ClassB is missing the Q_OBJECT macro; this means that from the point of view of Qt's metatype system, it is identical to ClassA . Adding Q_OBJECT to ClassB will solve the issue.

I think Angew answered.

The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, and the dynamic property system.

The C++ source file generated by moc must be compiled and linked with the implementation of the class.

More information here: http://woboq.com/blog/how-qt-signals-slots-work.html

Also you should test the return of the connect (true/false) and assert in case of failure. Avoid a lot of issues...

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