Qt | C++ connect not being triggered

95 Views Asked by At

I'm trying to play with basic signal/slot in C++.

Here is my Network-Manager, which will trigger the event:

class NetworkManager : public QObject {
Q_OBJECT
public:
    explicit NetworkManager(QApplication* application);
    void OnFinished(QNetworkReply *reply);
    ...
signals:
    void OnReceived();
};

And in Display-Manager, this class will receive the event:

class DisplayManager : public QObject{
Q_OBJECT
public:
    explicit DisplayManager(QApplication *app);
    void ChangeWallPaper();
public slots:
    void ReceiveData();
};

And I'm trying to connect from another class:


Manager::Manager(QApplication *application, NetworkManager networkManager, DisplayManager displayManager)
: networkManager(application),displayManager(application) {
    ...
    connect(&networkManager, &NetworkManager::OnReceived, &displayManager, &DisplayManager::ReceiveData);
}

And in these class's implementation:

void DisplayManager::ReceiveData() {
    std::cout << "being called" << std::endl;// to check if this is being called
}

void NetworkManager::OnFinished(QNetworkReply *reply) {
    OnReceived(); // to trigger
}
// OnReceived() not implemented as it just a signal

What am I missing here? Why is the ReceiveData function not being called?

2

There are 2 best solutions below

0
On BEST ANSWER

Here is the solution :

Manager::Manager(QApplication *application,
                 NetworkManager _networkManager,
                 DisplayManager _displayManager)
        : networkManager(application)
        , displayManager(application)
{
    ...
    connect(&networkManager, &NetworkManager::OnReceived,
            &displayManager, &DisplayManager::ReceiveData);
}
5
On

Consider your Manager constructor...

Manager::Manager(QApplication *application,
                 NetworkManager networkManager,
                 DisplayManager displayManager)
    : networkManager(application)
    , displayManager(application)
{
    ...
    connect(&networkManager, &NetworkManager::OnReceived,
            &displayManager, &DisplayManager::ReceiveData);
}

You pass the addresses of locally scoped variables networkManager and displayManager to connect. The connection will be destroyed as soon as those temporary variables go out of scope when the constructor completes.

Try passing networkManager and displayManager either by reference or pointer.