Qt连接函数
我正在尝试用 C++ 编写 Qt GUI 程序。这是代码:
sample.h:
#ifndef SAMPLE_H
#define SAMPLE_H
#include <QtGui/QApplication>
#include <QtGui/QPushButton>
#include <QtGui/QWidget>
#include <QtGui/QGridLayout>
#include <QtGui/QLineEdit>
#include <qobject.h>
class Sample : public QObject
{
Q_OBJECT
public:
Sample();
public slots:
void buttonPressed();
private:
QWidget *widget;
QGridLayout *layout;
QLineEdit *le;
QPushButton *button;
};
#endif // SAMPLE_H
sample.cpp:
#include "sample.h"
Sample::Sample()
{
widget = new QWidget();
widget->setWindowTitle("Sample");
layout = new QGridLayout();
le = new QLineEdit();
button = new QPushButton();
button->setText("Button");
connect(button, SIGNAL(clicked()), this, SLOT(buttonPressed()));
layout->addWidget(le, 0, 0);
layout->addWidget(button, 1 , 0);
widget->resize(300, 300);
widget->setLayout(layout);
widget->show();
}
void Sample::buttonPressed(){
le->setText("pressed");
}
我在构建时收到此错误:
error: undefined reference to `vtable for Sample'
我正在使用官方Qt网页上的QtCreator。
有人知道该怎么做才能让它发挥作用吗?非常感谢您的回复:)
I'm trying to program a Qt GUI in C++. Here is the code:
sample.h:
#ifndef SAMPLE_H
#define SAMPLE_H
#include <QtGui/QApplication>
#include <QtGui/QPushButton>
#include <QtGui/QWidget>
#include <QtGui/QGridLayout>
#include <QtGui/QLineEdit>
#include <qobject.h>
class Sample : public QObject
{
Q_OBJECT
public:
Sample();
public slots:
void buttonPressed();
private:
QWidget *widget;
QGridLayout *layout;
QLineEdit *le;
QPushButton *button;
};
#endif // SAMPLE_H
sample.cpp:
#include "sample.h"
Sample::Sample()
{
widget = new QWidget();
widget->setWindowTitle("Sample");
layout = new QGridLayout();
le = new QLineEdit();
button = new QPushButton();
button->setText("Button");
connect(button, SIGNAL(clicked()), this, SLOT(buttonPressed()));
layout->addWidget(le, 0, 0);
layout->addWidget(button, 1 , 0);
widget->resize(300, 300);
widget->setLayout(layout);
widget->show();
}
void Sample::buttonPressed(){
le->setText("pressed");
}
I obtain this error when building:
error: undefined reference to `vtable for Sample'
I'm using QtCreator from official Qt webpage.
Does anybody know what to do to make it work? Thank you very much for your responses :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果在编写并编译类后添加 Q_OBJECT 宏,通常会发生这种错误。重新运行 qmake 通常会修复它。
This kind of error usually occurs if you add the Q_OBJECT macro after having written and compiling your class. Rerunning qmake will usually fix it.