1
這是使用QObject.moveToThread實現PyQt多線程的程序的簡化版本。基本上,我在單獨的線程上查詢網頁並提取HMTL內容。從Windows cmd或IDLE運行而不是從PyCharm運行時,「QThread:線程仍在運行時被銷燬」?
我得到這個問題,從IDLE或Windows命令行運行代碼掛起蟒蛇。 Windows cmd顯示「QThread:線程仍在運行時銷燬」。但是,如果我從Pycharm運行它,一切正常。
你可以得到的.ui文件here
任何想法?
import requests
import sys
from PyQt4 import QtGui, uic
from PyQt4.QtCore import QObject, pyqtSlot, pyqtSignal, QThread
qtCreatorFile = "window.ui"
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class HttpClient(QObject):
finished = pyqtSignal(str)
def __init__(self):
QObject.__init__(self)
@pyqtSlot()
def retrieve_page(self, url):
response = requests.get(url)
self.finished.emit(response.text)
class HtmlGetter(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.go_button.clicked.connect(self.query_page)
def query_page(self):
http_client = HttpClient()
temp_thread = QThread()
http_client.moveToThread(temp_thread)
temp_thread.started.connect(
lambda: http_client.retrieve_page("http://www.google.com/"))
http_client.finished.connect(self.show_html)
# Terminating thread gracefully.
http_client.finished.connect(temp_thread.quit)
http_client.finished.connect(http_client.deleteLater)
temp_thread.finished.connect(temp_thread.deleteLater)
temp_thread.start()
def show_html(self, html_text):
print(html_text)
def main():
app = QtGui.QApplication(sys.argv)
window = HtmlGetter()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
我也遇到這個問題,每當我在Windows上運行多線程pyqt程序,特別是如果我嘗試Ctrl-C殺死它。 –