3

I wrote a little program with a my own class within the main.cpp. Here the code:

#include <QApplication>
#include <QPushButton>
#include <QLabel>

class MyWidget : public QWidget {
    //Q_OBJECT
public:
    MyWidget(QWidget* parent = 0);
    QLabel* label;
    QString string;

signals:
public slots:
    void setTextLabel();

};

void MyWidget::setTextLabel() {
    label->setText("Test");
}


MyWidget::MyWidget(QWidget* parent) 
     : QWidget(parent) {

}

int main(int argc, char** argv) {
    QApplication app(argc, argv);

    MyWidget widget;
    widget.show();

    return app.exec();
}

it seems work but not "completely". My slot doens't work. I suppose i have to put Q_OBJECT. BUT, doing so, I got a list of errors, like this:

undefined reference to `vtable for MyWidget'
........................................
collect2: error: ld returned 1 exit status
make: *** [mywidget] Error 1

I can I manage that? Where the problem?

m7913d
  • 10,244
  • 7
  • 28
  • 56
Mickey
  • 31
  • 2
  • Can you explain what you mean by ''My slot doesn't work''? In the example above the `MyWidget::setTextLabel` slot isn't actually used. Also note that your `MyWidget` constructor doesn't initialize the `label` member which will cause undefined behaviour. – G.M. Jul 21 '16 at 17:20
  • 1
    See this: http://stackoverflow.com/questions/34928933/why-is-important-to-include-moc-file-at-end-of-a-qt-source-code-file – hyde Jul 21 '16 at 19:55

2 Answers2

6

Signals and slots in Qt are managed through the moc: meta object compiler. Basically, the moc generates additional C++ code for each class containing the Q_OBJECT macro in order to implement effectively the signals and slots mechanisms. The additional code is then linked to the original class declaration.

The problem here is that your class is declared in main.cpp: this conflicts with how the moc is working with your code. You should declare your class in a separate header.

More about the moc

Edit: as hyde pointed, an alternative is to include in your cpp the file generated by the moc: Why is important to include “.moc” file at end of a Qt Source code file?

m7913d
  • 10,244
  • 7
  • 28
  • 56
rocambille
  • 15,398
  • 12
  • 50
  • 68
  • 3
    Not necessary, you don't need a .h file. See link under the question (and feel free to update your answer). – hyde Jul 21 '16 at 19:57
2

just append the line #include"main.moc" to your cpp source file should be enough.

More information:

m7913d
  • 10,244
  • 7
  • 28
  • 56
debao
  • 51
  • 6