简体   繁体   English

在 main.cpp 中定义信号和槽

[英]Define signals and slots inside main.cpp

I wrote a little program with a my own class within the main.cpp.我在 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.我想我必须放 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?问题出在哪里?

Signals and slots in Qt are managed through the moc: meta object compiler. Qt 中的信号和槽是通过 moc: 元对象编译器管理的。 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.基本上,moc 为每个包含 Q_OBJECT 宏的类生成额外的 C++ 代码,以便有效地实现信号和插槽机制。 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.这里的问题是你的类是在 main.cpp 中声明的:这与 moc 如何处理你的代码相冲突。 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?编辑:正如海德所指出的,另一种方法是在您的 cpp 中包含由 moc 生成的文件: 为什么在 Qt 源代码文件的末尾包含“.moc”文件很重要?

just append the line #include"main.moc" to your cpp source file should be enough.只需将#include"main.moc"行附加到您的 cpp 源文件就足够了。

More information:更多信息:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM