Q_OBJECT与否Q_OBJECT [英] Q_OBJECT or not Q_OBJECT
问题描述
我在main.cpp中编写了一个带有自己的类的小程序.这里的代码:
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();
}
似乎可以工作,但不能完全"使用.我的广告位无效.我想我必须放Q_OBJECT.但是,这样做,我得到了一个错误列表,像这样:
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?
推荐答案
Qt中的信号和插槽通过moc:元对象编译器进行管理.基本上,moc为包含Q_OBJECT宏的每个类生成附加的C ++代码,以便有效地实现信号和时隙机制.然后,附加代码将链接到原始类声明.
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.
这里的问题是您的类在main.cpp中声明:这与moc如何使用您的代码冲突.您应该在单独的标题中声明您的类.
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.
编辑:正如海德所指出的那样,另一种方法是在cpp中包含由moc生成的文件. 更多详细信息
as hyde pointed, an alternative is to include in your cpp the file generated by the moc; more details
这篇关于Q_OBJECT与否Q_OBJECT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!