Search code examples
qtsignals-slots

Unable to connect to signal from outside class in Qt


I have a EmitSignal class like this:

class EmitSignal : public QObject
{
    Q_OBJECT
public:
    EmitSignal() {
        emit emittedSignal();
        qDebug() << "Signal emitted";
    }
signals:
    void emittedSignal();
}; 

And in ConnectSlot class, it's like this:

class ConnectSlot : public QMainWindow
{
    Q_OBJECT
public:
    ConnectSlot() {
        connect(&emitSignalObject, &EmitSignal::emittedSignal, this, &ConnectSlot::connectToSlot);
    }

    EmitSignal emitSignalObject;

public slots:
    void connectToSlot() {
        qDebug() << "Connected";
    }
};

As you can see, I tried to connect the signal and slot, but it seems like the slot is not triggered. And the only output I got is: Signal emitted.

Why isn't the slot not connected and how do I do it properly?
Thanks


Solution

  • You are emitting a signal from EmitSignal's constructor. That constructor will run before the body of ConnectSlot's constructor begins execution.

    So the signal will be emitted before the connection is made.

    You need to change your code so that connections are made before signals get fired.