简体   繁体   中英

How an external module can display a message in Pyqt5 ui?

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}")

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}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM