qt | C++ 连接未被触发

Qt | C++ connect not being triggered

我正在尝试使用 C++ 中的基本 signal/slot。

这是我的 Network-Manager,它将触发事件:

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

并且在 Display-Manager 中,此 class 将接收事件:

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

我正在尝试从另一个连接 class :


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

在这些 class 的实现中:

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

我在这里遗漏了什么,为什么 ReceiveData 没有被调用?

考虑您的 Manager 构造函数...

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

您将局部作用域变量 networkManagerdisplayManager 的地址传递给 connect。当构造函数完成时,一旦这些临时变量超出范围,连接就会被销毁。

尝试通过引用或指针传递 networkManagerdisplayManager

这里是 the solution :

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