Python: PySide(Qt)異步獲取網頁源碼
阿新 • • 發佈:2018-09-05
5.1 是個 過程 fix update .text cat png dialog
學習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) flags = self.windowFlags() flags |= QtCore.Qt.WindowMinMaxButtonsHint flags |= QtCore.Qt.WindowCloseButtonHint self.setWindowFlags(flags) 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)異步獲取網頁源碼