Reputation: 193
I'm going through ZetCode's tutorial on PyQt4 GUI development. He gives the following code for making a toolbar -
self.toolBar = self.addToolBar('Exit')`
self.toolBar.addAction(exitAction)
and this to add a menuBar -
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(exitAction)
self here is that parent class which is a QtGui.QMainWindow.
I don't understand why he uses self.toolBar in the first example but doesn't use self.menuBar in the second example.
Upvotes: 0
Views: 55
Reputation: 3945
Adding self
at the starting of the variable name makes it the member variable or instance variable. When you create instance of mainWindow, menuBar already exists on QMainWindow
. Thus there is no need to save reference to menuBar in a member variable, because you can retrieve it any time in any part of your code by just calling self.menuBar()
. On the other hand, toolBar does not exist on mainWindow when you create it, you need to add it by calling self.addToolBar()
and save the reference to toolBar in a member variable in order to perform operations on toolBar in any part of the code.
Upvotes: 1
Reputation: 63787
In your second case as menuBar
is a reference to self.menuBar()
, the following code,
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(exitAction)
simply boils down to
fileMenu = self.menuBar().addMenu('&File')
fileMenu.addAction(exitAction)
which is not different from the first piece of code that you have
self.toolBar = self.addToolBar('Exit')`
self.toolBar.addAction(exitAction)
So, if you ask
I don't understand why he uses self.toolBar in the first example but doesn't use self.menuBar in the second example.
Its because of programming style and a sense of readability that varies from programmer to programmer.
Upvotes: 2
Reputation: 799580
menuBar = self.menuBar()
This indicates that self
already has a sense of its menu bar. This method call probably retrieves a pre-existing object, so as such there's no need to store it on the instance, nor would it necessarily be appropriate to do so (if e.g. it's actually someone else's menu bar and the class is just manipulating it).
Upvotes: 1
Reputation: 500963
In fact, the author does use self.menuBar()
:
menuBar = self.menuBar()
The above makes menuBar
refer to the object returned by self.menuBar()
.
Upvotes: 1