【发布时间】:2017-12-30 06:31:22
【问题描述】:
我有一个 Qt C++ 程序。我有一个主驱动程序MainWindow 和一个TCPClient 类。 TCPClient 类用于与远程服务器通信,通过 TCP 传输一些数据,请求处理数据并从服务器接收处理后的数据。在我的TCPClient 课程中,我使用QAbstractSocket 信号disconnected。当与服务器的连接断开时会发出此消息。在处理这个disconnect信号(ifDisconnected)的函数(槽)中,调用MainWindow的onCompletionCallback函数。现在我的问题是,在上述onCompletionCallback 完成执行后,如何防止将执行传输回TCPClient。以下是描述问题的不完整代码;
mainwindow.cpp
void MainWindow::on_connectButton_clicked()
{
std::function<void(void)> callback std::bind(&MainWindow::onCompletetionCallback, this);
tcpClient_ = new TCPClient(callback)->connectToServer(someData);
}
void MainWindow::onCompletetionCallback()
{
if(tcpClient_->isRequestSuccess())
{
QJsonDocument responseJson = tcpClient_->getResponse();
return; //When this finishes executing, I want to prevent the execution control to go back to TCPClient
}
}
TCPClient.cpp
void TCPClient::connectToServer(QJsonDocument requestJson)
{
// Removed code of other connect signals
connect(tcpSocket_, &QTcpSocket::disconnected, this, &TCPClient::ifDisconnected);
}
void TCPClient::ifDisconnected()
{
// Here the callback is called. After the callback finishes executing, I don't want execution to return to `TCPClient`.
onCompletionCallback_();
return;
}
我该如何解决这个问题。我需要使用信号disconnected,因为QAbstractSocket 没有提供任何实用功能来检查连接是否可用。
【问题讨论】: