在调用函数时,如何防止GUI冻结?(PyQT4、Python3)



问题背景:

我是PyQT4的新手。我正在用它开发一个程序,我正在进行网络抓取以将数据输入到我的程序中。当信息下载时,我的GUI锁定。我想在一个单独的后台线程中调用这个函数,也许可以使用QThread,但我很难理解QThread、一般的Qt以及插槽/信号通信方式。

我读过关于制作一个通用工作线程的文章,该线程将调用传递给它的任何函数。我不知道如何在我的主文件中实现它,以便我可以将函数作为后台进程运行。如果可以显示任何示例代码,请详细解释每一行,因为我不理解这个过程。

问题:

  1. 在函数运行时,如何防止GUI冻结
  2. 如何使用后台线程来运行类中的函数

代码:

我的ui是从Qt4Designer创建的外部文件加载的。

Github 上的完整文件

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))

main.py(主文件)

def connections():
    # If button is clicked, call summary(), which web scrapes 
    # for data. This could take 5-30 seconds, this freezes UI.
    ui.btnRefreshSummary.clicked.connect(lambda: summary())
# Refresh items in gui
def refresh_ui():
    if summary_data != []:
        ui.valWatching.setText(summary_data[0])
        ui.valBidding.setText(summary_data[1])
        ui.valWon.setText(summary_data[2])
        ui.valNotWon.setText(summary_data[3])
        ui.valPurchases.setText(summary_data[4])
        ui.valInvoices.setText(summary_data[5])
def login():
    # Scrape website and login while in background; 
    # This locks up GUI until it completes.
    # Pretend this sleep command is the time it takes to login
    time.sleep(5)  # <-This would lock it up for 5 seconds
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    connections()
    # Load credentials from file.
    with open('login.txt') as f:
        credentials = f.readline().strip().split(':')
    f.closed
    # Login, download summary, then refresh the UI.
    b = Biddergy()
    b.login(credentials[0],credentials[1])
    summary_data = b.summary()
    b.logout()
    refresh_ui()
    sys.exit(app.exec_())

从示例代码中不清楚为什么connections()阻塞(给定它包含的代码),或者为什么login()不应该阻止(给定登录对话框通常是这样做的)。但是无论如何,您的示例中的worker类可以转换为QThread,如下所示:

class Worker(QThread):
    intReady = pyqtSignal(int)
    def run(self):
        for i in range(1, 10):
            time.sleep(1)
            self.intReady.emit(i)

然后它可以这样使用:

    # connections()
    # login()
    def slot(arg='finished'): print(arg)
    thread = Worker()
    thread.intReady.connect(slot)
    thread.finished.connect(slot)
    thread.start()

还有许多其他方法可以实现同样的目的,但哪种方法最合适,以及如何实际实现,取决于应用程序的工作细节。

有了这些更新的代码,我终于可以在后台启动我的函数了。现在开始学习如何使我的后台线程与主UI线程进行通信。非常感谢@ekhumuro对我的耐心。

#!/usr/bin/env python3
from PySide import QtGui, QtCore
from PySide.QtCore import QThread, QObject, Signal, Slot
from main_gui import Ui_MainWindow  # my UI from Qt4 Designer(pyside-uic)
from Scrapers import Biddergy       # My own class
import sys
import queue
class BiddergyWrapper(QThread):
    def __init__(self, q, loop_time=1.0/60):
        self.q = q
        self.timeout = loop_time
        super(BiddergyWrapper, self).__init__()
    def onThread(self, function, *args, **kwargs):
        self.q.put((function, args, kwargs))
    def run(self):
        while True:
            try:
                function, args, kwargs = self.q.get(timeout=self.timeout)
                function(*args, **kwargs)
            except queue.Empty:
                self.idle()
    def idle(self):
        pass
    def _summary(self):
        b.summary()
    def summary(self):
        self.onThread(self._summary)
    def _login(self):
        b.login()
    def login(self):
        self.onThread(self._login())
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    ui.btnRefreshSummary.clicked.connect(lambda: bw.summary())
    # Load credentials from file.
    with open('login.txt') as f:
        credentials = f.readline().strip().split(':')
    # Login, download summary, then refresh the UI.
    b = Biddergy(credentials[0], credentials[1])
    request_queue = queue.Queue()
    bw = BiddergyWrapper(request_queue)
    bw.start()
    # Run QApplication
    app.exec_()
    # Begin "Graceful stop?"
    bw.quit()
    b.logout()
    sys.exit()

最新更新