0

I have a Python module with two classes, MainWindow (which inherits from QMainWindow) and MyView (which inherits from QGraphicsView). In the MainWindow I have a MyView which should set some variables in the MainWindow class. So I figured I just put the reference to my MainWindow object into a global variable and let the MyView access it like that. Here's the code:

class MyView(QtGui.QGraphicsView):
    def __init__(self, parent = None):
        super(MyView, self).__init__(parent)

    def mousePressEvent(self, event):
        super(MyView, self).mousePressEvent(event)
        print "Mouse Pointer is currently hovering at: ", event.pos()
        global myapp
        print "myapp value is: ", myapp


myapp = None
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MainWindow()
    print "myapp assigned, value is: ", myapp
    myapp.show()
    sys.exit(app.exec_())

After clicking on the MyView the program output is this:

$ ./main.py 
Gtk-Message: Failed to load module "canberra-gtk-module"
myapp assigned, value is:  <__main__.MainWindow object at 0x7fc29e1ed640>
Mouse Pointer is currently hovering at:  PyQt4.QtCore.QPoint(172, 132)
myapp value is:  None

Why is this? I'm not setting "myapp" to a different value, in the posted code are all occurcences of it.

cronotk
  • 147
  • 10
  • you have `parent` in `MyView` to access `MainWindow` – furas Nov 25 '15 at 10:51
  • The example code is very misleading, because it does not produce the stated output. I would guess that the real reason your code doesn't work is because you are trying to import from the main script. – ekhumoro Nov 25 '15 at 17:02

2 Answers2

1

You are not lloking for the global keyword here. Take a look at this post to see a nice explanation about the global keyword.

In this case you simply need to access the global myapp created in the main module, like so:

globals()['myapp']
Community
  • 1
  • 1
rll
  • 5,509
  • 3
  • 31
  • 46
1

With PyQt, you can also use the parent() method.

If you define MyView with a parent MainWindow:

 # either in __main__
 myapp = MainWindow()
 myview= MyView(myapp)

 # or in the class MainWindow
 self.myView=MyView(self)

Then myview.parent() allows you to access myapp

>>> print(myView.parent())
<__main__.MainWindow object at 0x7f02869b2678>
Mel
  • 5,837
  • 10
  • 37
  • 42
  • Luckily for me, Qt Designer makes the object instantiation, and it does the right thing in my case. The access through the parent() worked perfectly, thank you. – cronotk Nov 25 '15 at 12:44