Issue
I am developing a UI with Python 3.7 PyQt5.
This UI has several buttons that execute some methods.
I create a separate module called « mymodules.py » which stores some methods. The buttons of my UI are calling these external methods.
These methods sometimes failed and I am displaying the error message in the log console. I would like to display these error messages on my UI.
How can I do that please? As my modules can’t access the elements of my UI.
You can easily reproduce this scenario with this code below to copy-paste in 2 separate files (one for the UI, one for the 'mymodules')
Code:
#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_()
mymodules2.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}")
Solution
Simplest method would be to pass label to function:
button_action.triggered.connect(lambda:self.onMyToolBarButtonClick(label))
Change the triggered function:
def onMyToolBarButtonClick(self,label):
mymodules2.MyPersonalMethod("https://google.com",label)
Finally use it in your module like this:
def MyPersonalMethod(url,label):
try:
print("Trying")
label.setText("Success")
except Exception as ex:
print(f"error : {ex}")
label.setText(f"error : {ex}")
Answered By - BlueGhost
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.