0

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...

2
  • You never defined self.b, why do you think it exists? Did you meant self.btn3? Commented Apr 2, 2013 at 11:43
  • no "b" is the "btn3" from the user input, so I want to store the "btn3" string in the "b" variable and then use it as the instance Commented Apr 2, 2013 at 11:46

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.