python - In PyQT how to open a child window that has access to the parent's attributes? -
i have engine module contains several helper methods , attributes:
engine.py
class world: def __init__(self): # stuff def foo(a, b): c = + b # trivial example return c
then have main.py incorporates ui files (created in qtdesigner , converted .py using script have):
main.py
from pyqt4 import qtgui import design1 import design2 import engine class mainwindow(qtgui.qmainwindow, design1.ui_mainwindow): def __init__(self, parent=none): super(mainwindow, self).__init__(parent) self.setupui(self) self.world = engine.world() self.new_window_button.clicked.connect(self.open_new_window) def open_new_window(self): self.window_to_open = childwindow(self) self.window_to_open.show() class childwindow(qtgui.qmainwindow, design2.ui_mainwindow): def __init__(self, parent): super(childwindow, self).__init__(parent) self.setupui(self) print(self.world.foo(1, 2)) # trivial example def main(): app = qtgui.qapplication(sys.argv) window = mainwindow() window.show() app.exec()
if take out print
line, childwindow
opens fine. in error:
attributeerror: 'childwindow' object has no attribute 'world'
i know i'm doing silly can't figure out.
edited main.py
from pyqt4 import qtgui import design1 import design2 import engine class mainwindow(qtgui.qmainwindow, design1.ui_mainwindow): def __init__(self, parent=none): super(mainwindow, self).__init__(parent) self.setupui(self) self.world = engine.world() self.new_window_button.clicked.connect(self.open_new_window) def open_new_window(self): self.window_to_open = childwindow(self) self.window_to_open.show() class childwindow(qtgui.qmainwindow, design2.ui_mainwindow): def __init__(self, parent): super(childwindow, self).__init__(parent) self.setupui(self) print(self.parent().world.foo(1, 2)) # trivial example def main(): app = qtgui.qapplication(sys.argv) window = mainwindow() window.show() app.exec()
i error:
typeerror: foo() takes 2 positional arguments 3 given
the childwindow
class not have attribute world, can access through the parent()
function, returns parent since have used following statement: self.window_to_open = childwindow (self)
you must change
self.world.foo(1, 2)
to
self.parent().world.foo(1, 2)
your method must declared static since not use self parameter.
class world: def __init__(self): # stuff @staticmethod def foo(a, b): c = + b # trivial example return c
or
def foo(self, a, b): c = + b # trivial example return c
Comments
Post a Comment