Qt连接函数

发布于 2024-12-10 08:56:04 字数 1294 浏览 1 评论 0原文

我正在尝试用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不奢求什么 2024-12-17 08:56:04

如果在编写并编译类后添加 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文