Dániel Nagy
Dániel Nagy

Reputation: 35

Signals and Slots issue in inherited object [Qt5]

I have created a MySoundEffect class because I wanted to enhance its isPlaying() function by making it capable to return the elapsed time since the play was started. So I did what you see in the code.

The problem is, the connect in the constructor throws an error. It acts as if I was connect to the parent's asetTimer() slot which does not exist of course. I checked the this pointer with debugger at runtime and it points to a MySoundEffect object.

What am I doing wrong?

.h

#ifndef MYSOUNDEFFECT_H
#define MYSOUNDEFFECT_H

#include <QSoundEffect>
#include <QElapsedTimer>

class MySoundEffect : public QSoundEffect
{
    QElapsedTimer* timer;

public slots:
    void asetTimer();

public:
    MySoundEffect();
    ~MySoundEffect();

    int isPlaying();
};

#endif // MYSOUNDEFFECT_H

.cpp

#include "mysoundeffect.h"

MySoundEffect::MySoundEffect() : QSoundEffect()
{
    timer = new QElapsedTimer();
    connect(this,SIGNAL(playingChanged()), this, SLOT(asetTimer()));
}

void MySoundEffect::asetTimer(){
    if (QSoundEffect::isPlaying() == true){
        timer->restart();
    }
}

int MySoundEffect::isPlaying(){
    if (QSoundEffect::isPlaying() == true){
        return timer->elapsed();
    }
    else{
        return -1;
    }
}

MySoundEffect::~MySoundEffect(){
    delete timer;
}

error:

QObject::connect: No such slot QSoundEffect::asetTimer() in ../rob3/mysoundeffect.cpp:6

Upvotes: 2

Views: 460

Answers (2)

Jablonski
Jablonski

Reputation: 18514

Add Q_OBJECT macro:

class MySoundEffect : public QSoundEffect
{
    Q_OBJECT
    //...

And run qmake. Without this macro moc (meta-object compiler) can't found your class and can't create slots and signals, so compiler shows you this error that there is no such slot.

More information: http://qt-project.org/doc/qt-4.8/metaobjects.html

Also you wrote that you use Qt5, so it is good to know that there is new syntax

http://qt-project.org/wiki/New_Signal_Slot_Syntax

Which allows you to catch many errors in more informative way(such as missed macro or different types) and do this at compile time.

Upvotes: 2

madduci
madduci

Reputation: 2893

You forgot the magic keyword Q_OBJECT before the constructor. Without it, the signal/slot mechanism cannot work.

Upvotes: 5

Related Questions