在 main.cpp 中定义信号和槽 [英] Define signals and slots inside main.cpp

查看:38
本文介绍了在 main.cpp 中定义信号和槽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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.

更多关于 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?

这篇关于在 main.cpp 中定义信号和槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆