引子
最近有需求要在 PyQt 中请求一个链接, 因为比较简单直接用 urllib2 处理了, 但是 urllib2 在 有延时的时候会造成 GUI 界面卡死. 所以今天研究研究 QtNetwork 模块.
QtNetwork 中的请求在 PyQt 中都是异步的.
简单的请求 QHttp
发起一个GET请求
PyQt4.QtNetwork.QHttp
可以发起一个简单请求, 需要注意的是这个对象需要通过调用 setHost
设置请求主机, 然后 调用 get
/post
传入 path
才能正常使用.
#!/usr/bin/env python # -*- coding:utf-8 -*- from PyQt4 import QtGui, QtCore, QtNetwork class MainWidget(QtGui.QWidget): def __init__(self, parent=None): super(MainWidget, self).__init__(parent=parent) self.http = QtNetwork.QHttp(parent=self) # 绑定 done 信号 self.http.done.connect(self.on_req_done) self.url = QtCore.QUrl("http://linuxzen.com/") # 设置主机 self.http.setHost(self.url.host(), self.url.port(80)) self.getId = self.http.get(self.url.path()) def on_req_done(self, error): if not error: print "Success" print self.http.readAll() else: print "Error" if __name__ == "__main__":