I try to organize my code and therefore put some stuff into modules.
I would like several variables,, such as a statusBar()
, in the main code section to be altered by imported modules.
I made a quick minimal working example to show what I mean:
Here is my main.py:
from PyQt4 import QtGui
import module
import sys
class ApplicationWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
self.statusBar().showMessage("Main window initalized")
module.Test()
def main():
app = QtGui.QApplication(sys.argv)
form = ApplicationWindow()
form.show()
app.exec_()
if __name__ == "__main__":
main()
Here is module.py:
from PyQt4 import QtGui
class Test(QtGui.QMainWindow):
def __init__(self):
super(Test, self).__init__()
print 'hello'
self.statusBar().showMessage("Test module called", 6000)
The code prints "hello"
and does not throw me any error, so I assume the module is successfully imported and Test is initialized, but it does not alter the statusBar()
in my ApplicationWindow somehow. How can I achieve that? It's probably a silly mistake, so sorry in advance for bothering you!
the Test
class have to reference to the ApplicationWindow
class.
self.statusBar().showMessage("Test module called", 6000)
will set a message on the status bar for the window of Test
(A window that is lost to the void since it is never made visible or assigned to any variable)
Passing an instance of ApplicationWindow
to Test
would be one way to do what you want. Test
also does not need to inherit from QtGui.QMainWindow
for this.
from PyQt4 import QtGui
import module
import sys
class ApplicationWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
self.statusBar().showMessage("Main window initalized", 6000)
module.Test(self)
def main():
app = QtGui.QApplication(sys.argv)
form = ApplicationWindow()
form.show()
app.exec_()
if __name__ == "__main__":
main()
# module.py
class Test(object):
def __init__(self, parent):
print 'hello'
parent.statusBar().showMessage("Test module called", 6000)