在下载短文件期间阻止Qt应用程序

Jér*_*ôme 8 qt

我正在使用Qt4编写应用程序.

我需要从给定的http地址下载一个非常短的文本文件.

该文件很短,我的应用程序需要能够继续,所以我想确保下载是阻止的(如果文件未找到/不可用,将在几秒钟后超时).

我想使用QHttp :: get(),但这是一种非阻塞方法.

我以为我可以使用一个线程:我的应用程序将启动它,并等待它完成.线程将处理下载并在下载文件或超时后退出.

但我无法使其发挥作用:

class JSHttpGetterThread : public QThread
{
  Q_OBJECT

public:
  JSHttpGetterThread(QObject* pParent = NULL);
  ~JSHttpGetterThread();

  virtual void run()
  {
    m_pHttp = new QHttp(this);
    connect(m_pHttp, SIGNAL(requestFinished(int, bool)), this, SLOT(onRequestFinished(int, bool)));

    m_pHttp->setHost("127.0.0.1");
    m_pHttp->get("Foo.txt", &m_GetBuffer);
    exec();
  }

  const QString& getDownloadedFileContent() const
  {
    return m_DownloadedFileContent;
  }

private:
  QHttp* m_pHttp;

  QBuffer m_GetBuffer;
  QString m_DownloadedFileContent;

private slots:
  void onRequestFinished(int Id, bool Error)
  {
    m_DownloadedFileContent = "";
    m_DownloadedFileContent.append(m_GetBuffer.buffer());
  }
};
Run Code Online (Sandbox Code Playgroud)

在创建线程以启动下载的方法中,以下是我正在做的事情:

JSHttpGetterThread* pGetter = new JSHttpGetterThread(this);
pGetter->start();
pGetter->wait();
Run Code Online (Sandbox Code Playgroud)

但这不起作用,我的应用程序一直在等待.它看起来很亮,从来没有调用'onRequestFinished'.

任何的想法 ?

有没有更好的方法来做我想做的事情?

Dav*_*ben 5

您可以进入一个调用以下命令的循环,而不是使用线程processEvents

while (notFinished) {
   qApp->processEvents(QEventLoop::WaitForMore | QEventLoop::ExcludeUserInput);
}
Run Code Online (Sandbox Code Playgroud)

其中notFinished是可以从插槽设置的标志onRequestFinished

ExcludeUserInput将确保在等待时忽略 GUI 相关事件。


Phi*_*ent 5

稍晚但是:不要使用这些等待循环,正确的方法是使用来自QHttp的done()信号.

来自我所看到的requestFinished信号仅适用于您的应用程序完成请求时,数据可能仍在下降.

您不需要新线程,只需设置qhttp:

httpGetFile= new QHttp();
connect(httpGetFile, SIGNAL(done(bool)), this, SLOT(processHttpGetFile(bool)));
Run Code Online (Sandbox Code Playgroud)

另外,不要忘记刷新processHttpGetFile中的文件,因为它可能不在磁盘上.