[英]How an external module can display a message in Pyqt5 ui?
我正在使用 Python 3.7 PyQt5 開發用戶界面。
這個 UI 有幾個按鈕來執行一些方法。
我創建了一個名為“mymodules.py”的單獨模塊,其中存儲了一些方法。 我的 UI 的按鈕正在調用這些外部方法。
這些方法有時會失敗,我在日志控制台中顯示錯誤消息。 我想在我的 UI 上顯示這些錯誤消息。
請問我該怎么做? 由於我的模塊無法訪問我的 UI 的元素。
您可以使用下面的代碼輕松重現此場景,以復制粘貼到 2 個單獨的文件中(一個用於 UI,一個用於“mymodules”)
代碼:
#main UI
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QPushButton, QToolBar, QAction, QCheckBox, QStatusBar
from PyQt5.QtCore import Qt, QSize
import mymodules2
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("My Awesome App")
label = QLabel("THIS IS AWESOME!!!")
label.setAlignment(Qt.AlignCenter)
self.setCentralWidget(label)
toolbar = QToolBar("My main toolbar")
toolbar.setIconSize(QSize(16,16))
self.addToolBar(toolbar)
button_action = QAction(QIcon("bug.png"), "Your button", self)
button_action.setStatusTip("This is your button")
button_action.triggered.connect(self.onMyToolBarButtonClick)
button_action.setCheckable(True)
toolbar.addAction(button_action)
def onMyToolBarButtonClick(self):
"""
This method import mymodules.py and execute MyPersonalMethod()
"""
mymodules2.MyPersonalMethod("https://google.com")
# I need this method above to display in label UI "label" any error message produced by the method
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
我的模塊2.py
import webbrowser
def MyPersonalMethod(url):
#DO 1 thing
try:
chrome_path = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path))
webbrowser.get('chrome').open_new_tab(url)
except Exception as ex:
print(f"error : {ex}")
#Here I would like to return the message error in the label of ui in order to display it immediately
# Do a second thing whatever happened before
try:
print("We suppose to have open google.com!?")
except Exception as ex:
print(f"error : {ex}")
最簡單的方法是將 label 傳遞給 function:
button_action.triggered.connect(lambda:self.onMyToolBarButtonClick(label))
更改觸發的function:
def onMyToolBarButtonClick(self,label):
mymodules2.MyPersonalMethod("https://google.com",label)
最后在你的模塊中使用它,如下所示:
def MyPersonalMethod(url,label):
try:
print("Trying")
label.setText("Success")
except Exception as ex:
print(f"error : {ex}")
label.setText(f"error : {ex}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.