加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – Q_OBJECT与否Q_OBJECT

发布时间:2020-12-16 10:03:31 所属栏目:百科 来源:网络整理
导读:我在main.cpp中用自己的类编写了一个小程序.这里的代码: #include QApplication#include QPushButton#include QLabelclass MyWidget : public QWidget { //Q_OBJECTpublic: MyWidget(QWidget* parent = 0); QLabel* label; QString string;signals:public s
我在main.cpp中用自己的类编写了一个小程序.这里的代码:

#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.但是,这样做,我得到了一个错误列表,如下所示:

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

我可以管理吗?哪里有问题?

解决方法

Qt中的信号和插槽通过moc:meta对象编译器进行管理.基本上,moc为包含Q_OBJECT宏的每个类生成额外的C代码,以便有效地实现信号和时隙机制.然后将附加代码链接到原始类声明.

这里的问题是你的类在main.cpp中声明:这与moc如何处理你的代码有冲突.您应该在单独的标题中声明您的类.

More about the moc

编辑:正如hyde指出的,另一种方法是在你的cpp中包含moc生成的文件; more details

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读