我創建了一個輕量級瀏覽器來查看 PyQt5 應用程式中的 plotly .html 檔案,而不是在默認瀏覽器中,使用基于其他問題的 QWebEngineView,例如:Using a local file in html for a PyQt5 webengine
查看器可以作業,但是當打開多個視窗并顯示多個繪圖時,嘗試將其中一個繪圖保存為 .png 檔案會導致打開多個保存檔案對話框(自程式開始運行以來已打開的每個視窗都有一個對話框)。
我嘗試對此進行除錯,在下載請求之后似乎跳轉到 sys.exit(app.exec_()),然后再次回傳下載請求。盡管打開了幾個對話框,但實際上只保存了一個繪圖。
有沒有辦法確保只創建一個對話框?
要重現,請運行以下代碼并單擊繪制按鈕 2 次或更多次,創建多個視窗。使用 plotly “將繪圖下載為 png”選項,保存繪圖后,會顯示一個或多個附加的保存檔案對話框。
import os
import sys
from pathlib import Path
import plotly
import plotly.express as px
from PyQt5 import QtCore, QtWidgets
from PyQt5 import QtWebEngineWidgets, QtGui
user_profile = Path(os.environ.get("USERPROFILE"))
APP_DATA_FOLDER = user_profile / "AppData" / "Local" / "program"
APP_DATA_FOLDER.mkdir(parents=True, exist_ok=True)
class PlotlyViewer(QtWebEngineWidgets.QWebEngineView):
"""A lightweight browser used to view Plotly
figures without relying on an external browser.
"""
def __init__(
self, fig, title="Plot Viewer", count=0, download_directory=None
):
super().__init__()
self.windows = []
# Create a temporary html file containing the plot
self.file_path = str(APP_DATA_FOLDER / f"temp{count}.html")
plotly.offline.plot(
fig, filename=self.file_path, auto_open=False,
)
# Open the html file with the PlotlyViewer
self.load(QtCore.QUrl.fromLocalFile(self.file_path))
self.setWindowTitle(title)
self.resize(1000, 600)
# When a downloadRequest is received, run the download_file method
self.page().profile().downloadRequested.connect(self.download_file)
def closeEvent(self, event):
# When the plot is closed, delete the temporary file
os.remove(self.file_path)
@QtCore.pyqtSlot(QtWebEngineWidgets.QWebEngineDownloadItem)
def download_file(self, download):
# Get a save_file_dialog... For some reason this happens twice!
plot_path, _ = QtWidgets.QFileDialog.getSaveFileName(
None, "Save Plot As...", str(user_profile), "Image (*.png)"
)
if plot_path:
download.setPath(plot_path)
download.accept()
@staticmethod
def save_file_dialog(export_dir):
file_path, _ = QtWidgets.QFileDialog.getSaveFileName(
None, "Save Plot As...", export_dir, "Image (*.png)"
)
return file_path
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setFixedSize(150, 100)
MainWindow.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_plot = QtWidgets.QPushButton(self.centralwidget)
self.btn_plot.setGeometry(QtCore.QRect(0, 0, 70, 23))
self.btn_plot.setObjectName("btn_plot")
self.btn_plot.setText("plot")
self.connect_slots()
def connect_slots(self):
self.btn_plot.clicked.connect(self.create_plot)
def create_plot(self):
fig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])
browser_title = "a window title"
plot_window = PlotlyViewer(fig, browser_title, download_directory=user_profile)
plot_window.windows.append(plot_window)
plot_window.show()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
uj5u.com熱心網友回復:
默認情況下,所有 QWebEnginePages 共享相同的 QWebEngineProfile,這意味著self.page().profile()將始終回傳相同的組態檔物件。
Qt 連接總是累積的,即使對于相同的目標槽/函式:將信號連接到同一個函式兩次會導致每次發出信號時呼叫該函式兩次。
由于您每次創建新實體時都連接到同一組態檔的信號,因此每次請求下載時都會為每個實體呼叫。PlotlyViewerdownload_file
你有三種可能:
- 使用 , 連接信號一次
defaultProfile(),并從 PlotlyViewer 類外部連接; - 為每個視圖創建一個新的獨立組態檔(類似于“私人模式”):
self.profile = QWebEngineProfile()
self.setPage(QWebEnginePage(profile))
self.profile.downloadRequested.connect(self.download_file)
- 檢查
page()下載請求的 是否屬于視圖的頁面:
def download_file(self, download):
if download.page() != self.page():
return
# ...
其他重要說明:
- 大多數小部件會覆寫事件處理程式,呼叫基本實作始終是一種好習慣(除非您真的知道自己在做什么);您必須呼叫
super().closeEvent(event)覆寫closeEvent; - 由于您可能不打算重用已關閉的視圖,因此您應該始終洗掉它們,否則它們的資源將不必要地占用記憶體(并且會占用大量記憶體);添加
self.setAttribute(Qt.WA_DeleteOnClose),或__init__呼叫self.deleteLater();closeEvent() self.windows是一個實體屬性,添加plot_window實體是完全沒用的,因為它總是包含一個物件(實體本身);如果要跟蹤所有現有視窗,則應將串列創建為父物件的屬性(即主視窗)或類屬性(forPlotlyViewer);此外,考慮到上述幾點,您應該在視圖關閉和銷毀時洗掉參考;- 您不得編輯 pyuic 生成的檔案;除非您為了示例而這樣做,否則請注意這被認為是不好的做法,您應該遵循有關使用 Designer的官方指南;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/515870.html
