Search code examples
c++qtextend

How resolve undefined reference to vtable in c++ on QT


i have Ubuntu 14.04 , C++ , QT , I will extend the class QPushbutton , and i will to make a new Slot I do :

#include<QApplication>
#include<QDialog>
#include<QLabel>
#include <X11/Xlib.h>
#include<QVBoxLayout>
#include<iostream>
#include<QWidget>
#include<QPushButton>
#include <QThread>
#include <QGridLayout>
#include <QSplitter>
#include<QAbstractButton>
using namespace std;




class bot :  public QPushButton  {
   Q_OBJECT;

 public slots:
    void txt() {
        setText("hi");
         }


};


int main(int a , char * b[])
{
    QApplication application(a,b);
    QPushButton *button = new QPushButton();
    bot *l = new bot();
    button->setFixedSize(100,100);
    l->setText("sssssssssssssss");

    QVBoxLayout *ll  = new QVBoxLayout;
    ll->addWidget(l);
    ll->addWidget(button);
    QWidget x ;
    x.setLayout(ll);
    x.show();
    QObject::connect(button, SIGNAL(clicked()), l , SLOT( txt()) );

    return application.exec();


}

The Problem is :

/home/user/untitled6/sd.cpp:18: error: undefined reference to `vtable for bot'

how resolve the problem ???

my file.pro is :

SOURCES += \
    sd.cpp
QT += widgets

FORMS += \
    form.ui

Solution

  • Typically, errors like that can be resolved by running QMake. Anytime you create a new class that derives from QObject, Qt's model meta-object compiler (MOC) needs to auto-generate the code for the meta-class of the new class -- QMake ensures that this happens.

    If you are using Qt Creator, just select Run qmake from the Build menu.

    You may also have to run Clean project X or Clean all, also found in the Build menu.

    The MOC can be temperamental, so you need to do the following:

    • Move your QObject-derived class into a separate source and header file (In your case, create bot.h and bot.cpp, and move the class code there)
    • Separate declaration and definition of your slot code (define txt as bot::txt in bot.cpp)

    The MOC generates a corresponding meta-class file (moc_bot.cpp, in your case), and sometimes gets confused when there are multiple QObject-derived classes in one file. Best practice is to use one header and one source file for each QObject-derived class.

    If all else fails, you may need to delete the .pro.user file for your project, and exit and restart Qt Creator. Then from Build menu, choose Clean all, Run qmake, Rebuild All.