Peter Goldsborough
Peter Goldsborough

Reputation: 1388

storing instances in variables in python

In my Pyqt4 program I want to change the shortcut for some buttons. As I have quite a lot I thought of accessing a button through user input. I copied the relevant code snippets.

    self.btn3 = QtGui.QPushButton(self)

    b, ok = QtGui.QInputDialog.getText(self, 'Keyboard Mapping', 
            "Enter button number: ")  

so the user would, say, input "btn3", and then in another input dialog he'd specify the new shortcut. Finally, I want to change the button shortcut like this:

    self.b.setShortcut(newkey)

I get an error that my QMainWindow Class has no attribute "b".

Is there no way of storing an instance in a variable? Or maybe reading the variable or something? I'd be glad if you can help me...

Upvotes: 0

Views: 94

Answers (1)

Gareth Latty
Gareth Latty

Reputation: 89017

The issue here is that python doesn't take the value from b for the lookup when you do self.b.setShortcut(newkey), rather, it just looks for the name b.

You can do what you want using getattr():

getattr(self, b).setShortcut(newkey)

However, this is bad style and will generally be unsafe and cause problems. Instead, make a data structure that suits your need - here it would make sense to create a dictionary, for example:

self.widgets = {"btn3": QtGui.QPushButton(self)}
...
self.widgets[b].setShortcut(newkey)

Upvotes: 4

Related Questions