4
我有一個Python代碼,裏面有一些while循環,但我不知道如何使它與我的PyQt GUI一起工作 - 我只能運行Qt窗口或那個循環(但然後窗戶不顯示)。 有沒有解決這個問題的方法? 我讀過一些QThreads或QTimers,但我不知道如何使用它。PyQt - 在GUI中運行一個循環
我有一個Python代碼,裏面有一些while循環,但我不知道如何使它與我的PyQt GUI一起工作 - 我只能運行Qt窗口或那個循環(但然後窗戶不顯示)。 有沒有解決這個問題的方法? 我讀過一些QThreads或QTimers,但我不知道如何使用它。PyQt - 在GUI中運行一個循環
存在一個與您的問題非常相似的問題,Background thread with QThread in PyQt。答案有3種使用qthread
的獨特方法。
本教程可能是非常有益的,http://joplaete.wordpress.com/2010/07/21/threading-with-pyqt4/
這裏也是一個很好的例子:
import sys
import urllib2
from PyQt4 import QtCore, QtGui
class DownloadThread(QtCore.QThread):
def __init__(self, url, list_widget):
QtCore.QThread.__init__(self)
self.url = url
self.list_widget = list_widget
def run(self):
info = urllib2.urlopen(self.url).info()
self.list_widget.addItem('%s\n%s' % (self.url, info))
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.list_widget = QtGui.QListWidget()
self.button = QtGui.QPushButton("Start")
self.button.clicked.connect(self.start_download)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.button)
layout.addWidget(self.list_widget)
self.setLayout(layout)
def start_download(self):
urls = ['http://google.com', 'http://twitter.com', 'http://yandex.ru',
'https://stackoverflow.com/', 'http://www.youtube.com/']
self.threads = []
for url in urls:
downloader = DownloadThread(url, self.list_widget)
self.threads.append(downloader)
downloader.start()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.resize(640, 480)
window.show()
sys.exit(app.exec_())
你應該張貼你的代碼,你的循環。 – enginefree