[PyQt] QThread and event loop

Alexander Nestorov alexandernst at gmail.com
Sat Oct 2 15:51:50 BST 2010


I'm going to answer to myself.
I found a solution, and it was really simple!

Working code:


class Async(QThread):
  def run(self):
    self.jar = QNetworkCookieJar()
    self.manager = QNetworkAccessManager()
    self.manager.setCookieJar(self.jar)
    self.manager.finished.connect(self.downloadFinished)
    self.manager.authenticationRequired.connect(self.authenticationRequired)
    self.request = QNetworkRequest(self.url)
    self.request.setRawHeader("User-Agent", self.userAgent)
    self.reply = self.manager.get(self.request)
    self.reply.downloadProgress.connect(self.progressCallback)
    self.exec_()

  def download(self, url, userAgent = "Wget/1.12 (linux-gnu)", user = "",
password = ""):
    self.url = QUrl(url)
    self.userAgent = userAgent
    self.user = user
    self.password = password
    self.returnData = None
    self.moveToThread(self)        ### <------  Added line that fixes the
problem!
    self.start()

  def authenticationRequired(self, reply, authenticator):
    authenticator.setUser(self.user)
    authenticator.setPassword(self.password)

  def progressCallback(self, done, total):
    self.emit(QtCore.SIGNAL('progress(int, int)'), done, total)

  def downloadFinished(self, reply):
    print "dfinished"
    self.redirect =
reply.attribute(QNetworkRequest.RedirectionTargetAttribute).toUrl()
    if not self.redirect.isEmpty():
      self.request = QNetworkRequest(self.redirect)
      self.request.setRawHeader("User-Agent", self.userAgent)
      self.reply = self.manager.get(self.request)
      self.reply.downloadProgress.connect(self.progressCallback)
    else:
      self.emit(QtCore.SIGNAL('finished(PyQt_PyObject)'),
str(self.reply.readAll()))
      self.quit()


-- 
Alexander Nestorov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20101002/4e0cfbea/attachment.html>


More information about the PyQt mailing list