1

I have a method setupUi() in Ui_MainWindow in design.py (its a really long method created by PyQt Designer)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow): # really long method
        self.xyz
        ...
    ...

and would like to use it as if it were a method in my main file app.py in the ApplicationWindow class.

What I want to imitate:

class ApplicationWindow:
    def __init__(self, MainWindow, truss, *args, **kwargs):
        self.setupUi(MainWindow)
        [use self.xyz here]
        ...
    def setupUi(self, MainWindow): # same really long method I want here
        ...
    ...

What I tried:

from design import Ui_MainWindow

class ApplicationWindow:
    def __init__(self, MainWindow, truss, *args, **kwargs):
        Ui_MainWindow().setupUi(MainWindow) # this works
        [use self.xyz here] # this does not work
        ...
    ...

I want to use the variable self.xyz from Ui_MainWindow in the ApplicationWindow class.

But I get an AttributeError for self.xyz.

Again, the reason that I want it in a seperate file, is because it's very long.

I'm sure this is a simple fix, as modules work in a similar way. But for some reason it isn't working for me, any ideas?

How I call the function (everything is in OOP/Functional):

if __name__ == "__main__":
    import sys
    qapp = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()

    truss = FEModel3D
    app = ApplicationWindow(MainWindow, truss)

    MainWindow.show()
    sys.exit(qapp.exec_())

File structure:

master
├───app.py
├───...
└───design.py
LightninBolt74
  • 211
  • 4
  • 11

2 Answers2

1

You can accomplish this by creating a common parent for UI_MainWindow and ApplicationWindow (e.g. ParentWindow) and extracting setupUi into a class method of the ParentWindow.

so create in a new file e.g. parent.py:

class ParentWindow:
  def setupUi(self, window):
    # same definition

and now import ParentWindow to both classes and replace class UI_MainWindow(object): and class ApplicationWindow: with class UI_MainWindow(ParentWindow) and class ApplicationWindow(ParentWindow), respectively.

Armin
  • 168
  • 1
  • 1
  • 15
  • Do I need the parenthesis in the class definition? – LightninBolt74 Apr 13 '20 at 04:25
  • You would only use parenthesis in the class definition when specifying the parent class. So in `class UI_MainWindow(ParentWindow)` and `class ApplicationWindow(ParentWindow)`, but not in `class ParentWindow`. In regards to why you don't have to write `class ParentWindow(object)` you can see [this answer](https://stackoverflow.com/a/45062077/6282058). – Armin Apr 13 '20 at 11:23
0

I tried using a variable to connect the two classes and it worked!

app.py

class ApplicationWindow():
    def __init__(self, MainWindow, truss, *args, **kwargs):
        win = Ui_MainWindow()
        win.setupUi(MainWindow)
        self.xyz = win.xyz

design.py was the same.

LightninBolt74
  • 211
  • 4
  • 11