简体   繁体   中英

Qt, QCoreApplication and QFtp

I want to use QFtp for the first time and googled a lot to find out how it should be used. This, among others is a typical example:

#include <QCoreApplication>
#include <QFtp>
#include <QFile>

int main(int argc, char ** argv)
{
  QCoreApplication app(argc, argv);

  QFile *file = new QFile( "C:\\Devel\\THP\\tmp\\test.txt" );
  file->open(QIODevice::ReadWrite);

  QFtp *ftp = new QFtp();

  ftp->setTransferMode(QFtp::Active);
  ftp->connectToHost("ftp.trolltech.com"); 
  ftp->login();                           
  ftp->cd("qt");                     
  ftp->get("INSTALL",file);               
  ftp->close();

  QObject::connect(ftp, SIGNAL(done(bool)), &app, SLOT(quit()));

  int ret = app.exec();

  delete ftp;
  delete file;

  return ret;
}

The question:

As far as I understood, the QCoreApplication app is needed to handle the "done" signal, emmited upon finalization of ftp-get. Now, the ftp->get is called before the connect and even before the app handler is running at all (app.exec() is called afterwards).

What happens, if the file transfer has completed already before the "connect" statement? In fact, that will not happen, but I could put an artificial delay of, say 1 minute between ftp->close() and the connect(...). During this time, the ftp get will surely be finished. What would happen?

Note that QFtp is really only meant for legacy Qt applications and it is now suggested that QNetworkAccessManager and QNetworkReply are used instead, as detailed in the Qt documentation .

That being said, with your connect call being positioned after the connection to the FTP site and retrieving of the file, should the file be downloaded first, the 'quit' signal would never be reached. If you make the connection straight after creating the QFtp object, then this won't be an issue: -

QFtp *ftp = new QFtp();
QObject::connect(ftp, SIGNAL(done(bool)), &app, SLOT(quit()));

This guarantees that the 'quit' slot will be called when the QFtp object emits the 'done' signal.

QFtp *ftp = new QFtp();
QObject::connect(ftp, SIGNAL(done(bool)), &app, SLOT(quit()));

ftp->setTransferMode(QFtp::Active);
ftp->connectToHost("ftp.trolltech.com"); 
ftp->login();                           
ftp->cd("qt");                     
ftp->get("INSTALL",file);               
ftp->close();

int ret = app.exec();

In reality though, I would expect the connect in your example would complete before the machine had time to negotiate a connection to another server, login and start the download of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM