I'm an advanced beginner using Qt and I'm trying to write a console app that uses QFtp. The app itself is essentially just procedural code but because QFtp is asynchronous this is driving me crazy. I need to test that multiple ftp downloads are successful, but the code doesn't block so the test always fails. The best solution so far is to create a chain of signals and slots daisy chaining the ftp code and the procedural sections. It seems there has to be a better way. Any ideas?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can use QEventLoop to wait for a signal. Just connnect the signal to QEventLoop::quit()
, and then call QEventLoop::exec()
.
QFtp ftp;
QEventLoop eventLoop;
connect(&ftp, SIGNAL(commandFinished(int,bool)), &eventLoop, SLOT(quit()));
eventLoop.exec();
回答2:
As it's asynchronous you're best off tracking it through the signal and slots mechanism, but that does throw off your procedural logic. The only other default option for FTP in Qt is QNetworkAccessManager
but that's also asynchronous, so whichever you go for you're going to have to use the signal/slots system to track when it's done.
You could use QTcpSocket
and write your own FTP code, that allows you to block the calling thread until it returns with certain conditions, but you'll have to write significantly more code to do what you want to.