如何在一个过程中连续多次启动pyqt GUI?

2024-04-16 19:33:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我如何构建代码以在一个进程中连续多次运行pyqt GUI

(如果相关,请具体说明pyqtgraph)

上下文

在测量设备上执行长时间运行的数据捕获的python脚本(大for循环)。在每次捕获迭代期间,会出现一个新的GUI,并在主捕获代码运行时向用户显示测量设备的实时数据

我想这样做:

for setting in settings:
  measurement_equipment.start(setting)
  gui = LiveDataStreamGUI(measurement_equipment)
  gui.display()
  measurement_equipment.capture_data(300) #may take hours
  gui.close()

主要问题

我希望数据捕获代码成为主线程。然而pyqt似乎不允许这种架构,因为它的app.exec_()是一个阻塞调用,只允许每个进程创建一次GUI(例如,在上面的gui.display()


Tags: 数据代码脚本for进程displayguisetting
3条回答

如果您希望GUI在实时中不断更新,并且不被冻结,您有两种主要方法来实现这一点:

  1. 不时刷新GUI在耗时的函数中调用QApplication.processEvents()
  2. 创建一个单独的线程(我的意思是,QThread),在那里运行耗时的函数

我个人倾向于选择后一种方式Here是一个很好的教程,可以帮助您开始学习如何在Qt中执行多线程

查看您的代码:

...
gui.display()
measurement_equipment.capture_data(300) #may take hours
gui.close()
...

似乎您正在app.exec_内调用gui.display。很可能您必须将这两个函数解耦,并在gui.display之外和调用capture_data之后调用app.exec_。您还必须将新线程的finished信号连接到gui.close。它将是这样的:

...
gui.display() # dont call app.exec_ here
thread = QThread.create(measurement_equipment.capture_data, 300)
thread.finished.connect(gui.close)
app.exec_()
...

我希望这能帮助你,不要迟到

您只能有一个图形GUI线程。这意味着需要一些线程来捕获数据,并在需要时与图形应用程序同步数据。 我们需要知道GUI数据显示是显示实时数据还是仅显示一次

应用程序是在一个或多个前台线程上运行的可执行进程,每个前台线程还可以启动后台线程来执行并行操作或操作,而不会阻塞调用线程。应用程序将在所有前台线程结束后终止,因此,在您的情况下,至少需要一个前台线程,该线程是在调用app.exec_()语句时创建的。在GUI应用程序中,这是UI线程,您应该在其中创建并显示主窗口和任何其他UI小部件。当所有窗口小部件关闭时,Qt将自动终止您的应用程序进程

IMHO,您应该尽可能地遵循上面描述的正常流程,工作流可以如下所示:

Start Application > Create main window > Start a background thread for each calculation > Send progress to UI thread > Show results in a window after each calculation is finished > Close all windows > End application

另外,您应该使用ThreadPool来确保资源不会耗尽

下面是一个完整的示例:

import sys
import time
import PyQt5

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QRunnable, pyqtSignal, QObject
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QDialog


class CaptureDataTaskStatus(QObject):
    progress = pyqtSignal(int, int)  # This signal is used to report progress to the UI thread.
    captureDataFinished = pyqtSignal(dict)  # Assuming your result is a dict, this can be a class, a number, etc..


class CaptureDataTask(QRunnable):
    def __init__(self, num_measurements):
        super().__init__()

        self.num_measurements = num_measurements
        self.status = CaptureDataTaskStatus()

    def run(self):
        for i in range(0, self.num_measurements):
            # Report progress
            self.status.progress.emit(i + 1, self.num_measurements)
            # Make your equipment measurement here
            time.sleep(0.1) # Wait for some time to mimic a long action

        # At the end you will have a result, for example
        result = {'a': 1, 'b': 2, 'c': 3}

        # Send it to the UI thread
        self.status.captureDataFinished.emit(result)


class ResultWindow(QWidget):
    def __init__(self, result):
        super().__init__()

        # Display your result using widgets...
        self.result = result

        # For this example I will just print the dict values to the console
        print('a: {}'.format(result['a']))
        print('b: {}'.format(result['b']))
        print('c: {}'.format(result['c']))


class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.result_windows = []

        self.thread_pool = QtCore.QThreadPool().globalInstance()

        # Change the following to suit your needs (I just put 1 here so you can see each task opening a window while the others are still running)
        self.thread_pool.setMaxThreadCount(1)

        # You could also start by clicking a button, menu, etc..
        self.start_capturing_data()

    def start_capturing_data(self):
        # Here you start data capture tasks as needed (I just start 3 as an example)
        for setting in range(0, 3):
            capture_data_task = CaptureDataTask(300)
            capture_data_task.status.progress.connect(self.capture_data_progress)
            capture_data_task.status.captureDataFinished.connect(self.capture_data_finished)
            self.thread_pool.globalInstance().start(capture_data_task)


    def capture_data_progress(self, current, total):
        # Update progress bar, label etc... for this example I will just print them to the console
        print('Current: {}'.format(current))
        print('Total: {}'.format(total))

    def capture_data_finished(self, result):
        result_window = ResultWindow(result)
        self.result_windows.append(result_window)
        result_window.show()


class App(QApplication):
    """Main application wrapper, loads and shows the main window"""

    def __init__(self, sys_argv):
        super().__init__(sys_argv)

        self.main_window = MainWindow()
        self.main_window.show()


if __name__ == '__main__':
    app = App(sys.argv)   
    sys.exit(app.exec_())

相关问题 更多 >