PyQt - 在 GUI 中运行循环 [英] PyQt - running a loop inside GUI
问题描述
我有一个 Python 代码,里面有一些 while 循环,但我不知道如何让它与我的 PyQt GUI 一起工作 - 我只能运行 Qt 窗口或那个循环(但是 Windows 不显示).有什么解决办法吗?我读过一些 QThreads 或 QTimers,但我不知道如何使用它们.
I've got a Python code with some while loop inside, but I don't know how to make it work with my PyQt GUI - I can only run the Qt window or that loop (but then windows doesn't show). Is there any solution to this? I read about some QThreads or QTimers, but I don't have any idea how to use it.
推荐答案
有一个问题和你的很相似,PyQt 中带有 QThread 的后台线程.答案有 3 种使用 qthread
的独特方法.
There is a question that is very similar to yours, Background thread with QThread in PyQt. The answer has 3 unique methods to using a qthread
.
本教程可能非常有用,http://joplaete.wordpress.com/2010/07/21/threading-with-pyqt4/
这也是一个很好的例子:
Here is also a very good example:
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_())
这篇关于PyQt - 在 GUI 中运行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!