Print directly to a PyQt StatusBar

Question:

I have two classes. One for my GUI in PyQt6 and the other one that executes a function. In my interface, I have a PyQt StatusBar and a Button. When I press the button, I call the other class. I would like to be able to modify the statusBar message from this new class.

Here is a small example of code to reproduce the situation.

from PyQt6.QtWidgets import *
import sys


class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Python")
        self.setGeometry(60, 60, 200, 100)

        self.statusBar().showMessage("This is status bar.")

        button1 = QPushButton(self)
        button1.setText("Button1")
        button1.clicked.connect(self.button1_clicked)

        self.show()

    def button1_clicked(self):
        a = OtherClass
        a.Add(100, 200)

class OtherClass:
    def __init__(self):
        pass
    
    @staticmethod
    def Add(a, b):
        print(f"{a} + {b} = {a+b}")

if __name__ == '__main__':
    App = QApplication(sys.argv)
    window = Window()

    sys.exit(App.exec())

In this example, I want the statusBar to show the message "100 + 200 = 300".
I know that it is possible to send the statusBar as an argument to the new class and use it. But I don’t want to do that. I want my OtherClass to be empty of any PyQt elements.

It is possible to use print to replace logging.info. Is the same possible for statusbar().showMessage and print?

Asked By: Apollo11Mission

||

Answers:

It sounds like you are referring to a callback.

You can simply use a lambda and pass it into the Add method as a 3rd parameter.

For example:

from PyQt6.QtWidgets import *
import sys


class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Python")
        self.setGeometry(60, 60, 200, 100)

        self.statusBar().showMessage("This is status bar.")

        button1 = QPushButton(self)
        button1.setText("Button1")
        button1.clicked.connect(self.button1_clicked)

        self.show()

    def button1_clicked(self):
        a = OtherClass
        a.Add(100, 200, lambda x: self.statusBar().showMessage(x, 10000))

class OtherClass:
    def __init__(self):
        pass

    @staticmethod
    def Add(a, b, cb_func):
        cb_func(f"{a} + {b} = {a+b}")

if __name__ == '__main__':
    App = QApplication(sys.argv)
    window = Window()

    sys.exit(App.exec())

Or an even easier solution would be to do what is suggested in the comments, and simply return the value.

Answered By: Alexander
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.