Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blocking a Qt application during downloading a short file

Tags:

qt

I'm writing an application using Qt4.

I need to download a very short text file from a given http address.

The file is short and is needed for my app to be able to continue, so I would like to make sure the download is blocking (or will timeout after a few seconds if the file in not found/not available).

I wanted to use QHttp::get(), but this is a non-blocking method.

I thought I could use a thread : my app would start it, and wait for it to finish. The thread would handle the download and quit when the file is downloaded or after a timeout.

But I cannot make it work :

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());
  }
};

In the method creating the thread to initiate the download, here is what I'm doing :

JSHttpGetterThread* pGetter = new JSHttpGetterThread(this);
pGetter->start();
pGetter->wait();

But that doesn't work and my app keeps waiting. It looks lit the slot 'onRequestFinished' is never called.

Any idea ?

Is there a better way to do what I'm trying to do ?

like image 884
Jérôme Avatar asked Oct 30 '08 16:10

Jérôme


2 Answers

A little late but: Do not use these wait loops, the correct way is to use the done() signal from QHttp.

The requestFinished signal from what I have seen is just for when your application has finished the request, the data may still be on its way down.

You do not need a new thread, just setup the qhttp:

httpGetFile= new QHttp();
connect(httpGetFile, SIGNAL(done(bool)), this, SLOT(processHttpGetFile(bool)));

Also do not forget to flush the file in processHttpGetFile as it might not all be on the disk.

like image 81
Phil Hannent Avatar answered Oct 24 '22 03:10

Phil Hannent


Instead of using a thread you can just go into a loop which calls processEvents:

while (notFinished) {
   qApp->processEvents(QEventLoop::WaitForMore | QEventLoop::ExcludeUserInput);
}

Where notFinished is a flag which can be set from the onRequestFinished slot.

The ExcludeUserInput will ensure that GUI related events are ignored while waiting.

like image 28
David Dibben Avatar answered Oct 24 '22 03:10

David Dibben