1

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";
}
1
  • 1
    if you are creating the button and function in ClassB, why is the connect statement in ClassA? Commented Dec 5, 2013 at 20:34

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

classb.cpp:7: undefined reference to `vtable for ClassB'
@user2372976 And line 7 happens to be...? BTW, did you re-run MOC on the ClassB header after adding Q_OBJECT?
line 7 is: ClassB::ClassB(), what is MOC? :D
@user2372976 moc.exe, Qt's meta-object compiler. It basically means you have to re-create your buildsystem after you add Q_OBJECT to a file where it wasn't used previously. If you're using qmake, that means re-running qmake.
1

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.