Python: PySide(Qt)异步获取网页源码

时间:2021-05-03 18:29:59

学习PyQt UI编程笔记。相对PyQt来说,PySide资料为少。

此篇记录异步获取代码后,同步显示于界面窗体中,涉及线程网步,此为知识点。

直录代码:

# encoding: utf-8

from PySide.QtGui import *
from PySide.QtCore import *
from gethtml_ui import *
from options_ui import *
import threading # Make main window class
class OptionsDialog(QDialog):
def __init__(self, parent=None, title=''):
super(OptionsDialog, self).__init__(parent) self.setWindowFlags(Qt.Dialog | Qt.WindowCloseButtonHint | Qt.MSWindowsFixedSizeDialogHint)
self.ui = Ui_Options()
self.ui.setupUi(self)
self.setWindowTitle(title) class GetHtmlDialog(QDialog):
htmlGet = Signal(str) def __init__(self, parent=None):
super(GetHtmlDialog, self).__init__(parent) # 最大化&最小化按钮
self.setWindowFlags(Qt.Window)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.setWindowTitle('Get Html') self.ui.btnGet.setEnabled(False)
clipboard = QApplication.clipboard()
# url = clipboard.text()
# if url == '':
url = 'https://www.baidu.com'
self.ui.edtUrl.setText(url) # 同步更新内容
self.htmlGet.connect(lambda s: self.ui.txtHtml.setPlainText(s)) def get_html(self, url):
import urllib2 if not 'http' in url:
url = 'http://' + url
try:
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.9.5.1000 Chrome/39.0.2146.0 Safari/537.36')
res = urllib2.urlopen(req)
html = res.read().decode('utf-8')
# 同步到主线程
self.htmlGet.emit(html)
except BaseException, e:
self.updateHtml.emit(e.message)
finally:
self.ui.edtUrl.setEnabled(True)
self.ui.btnGet.setEnabled(True) @QtCore.Slot(str)
def on_edtUrl_textChanged(self, s):
self.ui.btnGet.setEnabled(s != '') @QtCore.Slot(QKeyEvent)
def edtUrl_keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Enter and self.ui.btnGet.isEnabled():
self.ui.btnGet.click() @QtCore.Slot()
def on_btnGet_clicked(self):
self.ui.edtUrl.setEnabled(False)
self.ui.btnGet.setEnabled(False)
t = threading.Thread(target=GetHtmlDialog.get_html, args=(self, self.ui.edtUrl.text()), name='thread')
t.start()
# self.get_html(self.ui.edtUrl.text()) @QtCore.Slot()
def on_btnClose_clicked(self):
app.exit() @QtCore.Slot()
def on_btnOptions_clicked(self):
od = OptionsDialog(self, self.ui.edtUrl.text())
# QDialog.Accepted
if od.exec_():
print 'yeah!'
else:
print 'cancel.' # End of main window class if __name__ == '__main__':
import sys app = QApplication(sys.argv)
ud = GetHtmlDialog()
ud.show()
sys.exit(app.exec_())

显示效果如图:

Python: PySide(Qt)异步获取网页源码

工欲善其事必先利其器,熟悉本不熟的东西,本是个摸索过程,希望能更多探索它的功能