在使用QFtp进行客户端编程时,对于如何正确在 ftp 命令结束后,执行相应的动作,网络上提供了一种方法,现摘要如下,代码来源:
void FtpWindow::commandFinished(int id, bool error)
{
Q_UNUSED(id);
QFtp::Command command = ftp->currentCommand();
switch (command) {
case QFtp::ConnectToHost: { // 连接 FTP 服务器
if (error) { // 发生错误
qDebug() << "Error " << ftp->error() << "ErrorString " << ftp->errorString();
QMessageBox::information(this, "FTP", QStringLiteral("无法连接到 FTP 服务器,请检查主机名是否正确!"));
ftp->abort();
ftp->deleteLater();
ftp = NULL;
} else {
qDebug() << QStringLiteral("登录 FTP 服务器");
}
break;
}
default:
break;
}
}
上述代码在命令结束的槽函数中,将传入的 id 进行屏蔽处理,然后获取当前 ftp 正在执行的命令,然后执行对应命令的处理步骤;但是,进入该槽函数的目的是处理执行完的命令,而不是正在执行的命令,这与设计是互相违背的;使用正在执行的命令这种思路,会导致命令队列执行结果的处理异常,而导致结果异常;正确的方式如下:
void FtpWindow::commandFinished(int id, bool error)
{
if (id = id_connect_to_host_) {
if (error) { // 发生错误
qDebug() << "Error " << ftp->error() << "ErrorString " << ftp->errorString();
ftp->abort();
ftp->deleteLater();
ftp = NULL;
} else {
qDebug() << QStringLiteral("登录 FTP 服务器");
}
}
else
{
// 其它...
}
}
其中,id_connect_to_host_ 为ConnectToHost函数执行时返回值,需要进行保存。