undefined reference to `Counter::valueChanged(int)‘

问题:

i'm trying to learn qt.this is my first example that I'm practicing.but i have this error:C:\Qt2\Qt5.2.1\Tools\QtCreator\bin\recognize_signal_slot\main.cpp:19: error: undefined reference to `Counter::valueChanged(int)'

I don't know what I should do..someone told me you should put your class in header file.but I couldn't understand what he said.can anyone tell me step by step.thank you so much.

here is my code in main.cpp :

     #include <QCoreApplication>
#include <QObject>

class Counter : public QObject
{

    int m_value;
public:
    int value() const { return m_value; }
public slots:
    void setValue(int value);
signals:
    void valueChanged(int newValue);
};
void Counter::setValue(int value)
{
    if (value != m_value) 
    {
        m_value = value;
        emit valueChanged(value);
    }
}
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Counter d, b;
      QObject::connect(&d, SIGNAL(valueChanged(int)),
                       &b, SLOT(setValue(int)));

     d.setValue(12);  // a.value() == 12, b.value() == 12

    return a.exec();
}

解答:

You signals & slots are not invoked by Meta-Object-Compiler (MOC).

Suggested reading: Why Does Qt Use Moc for Signals and Slots?.

Step 1. Add Q_OBJECT macro to the QObject derivatives that use signals & slots.

    class Counter : public QObject
    {
        Q_OBJECT     // <-----HERE

        int m_value;
    public:
        int value() const { return m_value; }
    public slots:
        void setValue(int value);
    signals:
        void valueChanged(int newValue);
    };

Step 2. move your class declaration to counter.h and implementation to counter.cpp. Since MOC searches header files that contain Q_OBJECT, it's better to keep your QObject classes and main well separate, even for a small test project.

Step 3. Clean all ---> run qmake ---> rebuild (qmake will automatically call MOC to translate signals & slots syntax into compilable C++ code)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值