从Dash回调内部显示PyQt5元素

2022-04-19 00:00:00 python python-3.x plotly-dash pyqt pyqt5

问题描述

在我的Python Dash应用程序中,我想显示一些PyQt5窗口弹出窗口。 这些是在回调中从内部激活的。

遗憾的是,当弹出窗口显示时,我在控制台中收到以下警告:

警告:未在主()线程中创建QApplication。

我的问题:如果从Python Dash回调内部调用,我如何在main()线程中创建一个QApplication?

下面您可以找到表示MWe的代码。如果运行此代码段,您将看到警告。显然,当从回调中激活QApplication时,它并不在主线程上运行(我猜测app.run_server()已经在主线程上运行)。如何修改它以使QApplication位于主线程中?

该示例类似于 Use Dash (plot.ly) in PyQt5 GUI 但不同(我需要Dash中的pyqt5,而不是pyqt5中的Dash)。


import os, dash
from PyQt5.QtWidgets import QApplication,QMainWindow
from PyQt5.QtCore import QCoreApplication
import dash_html_components as html
from dash.dependencies import Input, Output

class MainWindow(QMainWindow):
    #some Qpop up
    pass

app = dash.Dash()

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),
    #button which, if pressed, created a QApplication in a non-main thread
    html.Button("show pop up", id="button"),
    html.H2(children='', id='result')
    ])

#The callback which creates the pop up I want to show.
#This is activated when the button "show pop up" is pressed, and causes the warning to appear
@app.callback(
Output(component_id='result', component_property='children'),
[Input(component_id='button', component_property='n_clicks')]
)   
def popUp(n_clicks):
    if not n_clicks:
        raise dash.exceptions.PreventUpdate
    app = QCoreApplication.instance()
    if app is None:
        app = QApplication([os.getcwd()])
    mainWin = MainWindow()
    mainWin.show()
    app.exec_()
    return "You saw a pop-up"

if __name__ == '__main__':
    app.run_server(debug=False)

解决方案

逻辑是在辅助线程中运行Dash,并通过如下所示的信号向图形用户界面发送通知(此答案基于my other answer):

import functools
import os
import threading

from PyQt5 import QtCore, QtWidgets

import dash
import dash_html_components as html
from dash.dependencies import Input, Output


class MainWindow(QtWidgets.QMainWindow):
    closed = QtCore.pyqtSignal()

    def closeEvent(self, event):
        self.closed.emit()
        super().closeEvent(event)


class Manager(QtCore.QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._view = None

    @property
    def view(self):
        return self._view

    def init_gui(self):
        self._view = MainWindow()

    @QtCore.pyqtSlot()
    def show_popup(self):
        if self.view is not None:
            self.view.show()


qt_manager = Manager()

app = dash.Dash()

app.layout = html.Div(
    children=[
        html.H1(children="Hello Dash"),
        html.Button("show pop up", id="button"),
        html.H2(children="", id="result"),
    ]
)


@app.callback(
    Output(component_id="result", component_property="children"),
    [Input(component_id="button", component_property="n_clicks")],
)
def popUp(n_clicks):
    if not n_clicks:
        raise dash.exceptions.PreventUpdate

    loop = QtCore.QEventLoop()
    qt_manager.view.closed.connect(loop.quit)
    QtCore.QMetaObject.invokeMethod(
        qt_manager, "show_popup", QtCore.Qt.QueuedConnection
    )
    loop.exec_()

    return "You saw a pop-up"


def main():
    qt_app = QtWidgets.QApplication.instance()
    if qt_app is None:
        qt_app = QtWidgets.QApplication([os.getcwd()])
    qt_app.setQuitOnLastWindowClosed(False)
    qt_manager.init_gui()
    threading.Thread(
        target=app.run_server, kwargs=dict(debug=False), daemon=True,
    ).start()

    return qt_app.exec_()


if __name__ == "__main__":
    main()

相关文章