Search code examples
qtqt5

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

Solution

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