简体   繁体   中英

Calling a method from another class, while beeing in a method which already was called from the first class

I know there are tons of similar questions, but : for this case I haven't found the correct hint.

Overview

I'm writing a GUI (PyQt5). There is a main-class Ui_MainWindow() and a class Algorithm() where some calculations are made.

Ui_MainWindow() is called first and instances then Algorithm() .

My idea: in Ui_MainWindow() I call a method which is defined in Algorithm() called def update(self) . Now, in def update(self) I want to call a method def move(self) which is again in the first class Ui_MainWindow() .

My Problem: to call a method by another class, I need to instance it first, but I can not instance a class twice (at the beginning and in the second class), because that throws endless errors.

Illustrative example:

class Algorithm():
    def __init__(self, job_list):
        self.job_list = job_list
    def update(self):
        main = Ui_MainWindow() # this is the problem, I can not do this twice
        main.move()

class Ui_MainWindow():
    def __init__(self, *args, **kwargs):
        super(Ui_MainWindow, self).__init__(*args, **kwargs)
        self.setupUi()
    def setupUi(self):
        """ random code """
    def move(self):
        """ random code """

if __name__ == "__main__":
    main = Ui_MainWindow() # And I need it here. 
    main.show()

Please tell me, if my explanation is not clear.

I appreciate your help.

I think the fact that your main window doesn't inherit from QMainWindow is going to cause you problems, but disregarding that for now, here's how I'd suggest nesting your objects:

# define Ui_MainWindow first

class Algorithm():
    def __init__(self, job_list):
        self.job_list = job_list
        self.main_window = Ui_MainWIndow()

    def show(self):
        self.main_window.show()

    def update(self):
        self.main_window.move()

if __name__ == "__main__":
    # generate job_list somehow?
    algo = Algorithm(job_list)
    algo.show()

You could just add the UI_MainWindow object as an argument of your update function, like this:

def update(self, ui_Window):
    main = ui_Window
    main.move()

Then, to call it from your UI_MainWindow class, you do:

algorithm = Algorithm(job_list)
algorithm.update(self)

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