問題描述
我在 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++ 代碼,以便有效地實現(xiàn)信號和插槽機制.然后附加代碼鏈接到原始類聲明.
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 如何處理你的代碼相沖突.您應(yīng)該在單獨的標題中聲明您的類.
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.
更多關(guān)于 moc
正如海德所指出的,另一種方法是將 moc 生成的文件包含在您的 cpp 中:為什么在 Qt 源代碼文件的末尾包含.moc"文件很重要?一個>
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?
這篇關(guān)于在 main.cpp 中定義信號和槽的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!