So what you want to do is create a class which contains your code. You can create an instance of this class for each button or instead of each button. The two options are:
- Create a class which you pass in a reference to a button when you instantiate it. This is the simplest, but technically less clean approach.
- Subclass
QPushButton
and promote your buttons in Qt Designer to your new class
Note that the preferred solution is to subclass QPushButton
and then promote your widgets in Qt Designer to your new class. However, this can be a bit fiddly to work out. But, if you want to go down this route, you can, and you'll want to read this: Promote PyQt Widget
The class will look similar either way. You'll want something like this (for option 1)
class MyButton(object):
def __init__(self, button):
self.button = button
self.button.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.button.customContextMenuRequested.connect(self.buttonMenu)
self.button.clicked.connect(self.on_button_released)
@QtCore.pyqtSlot()
def on_button_released(self):
print ('Doing Stuff when clicking on Button A')
def buttonMenu(self, pos):
menu = QtGui.QMenu()
menu.addAction('First Action', lambda:self.FirstActionButton(objects))
menu.addAction('Second Action', lambda:self.SecondActionButton(objects))
menu.exec_(QtGui.QCursor.pos())
def FirstActionButton(self, objects):
print ('First Action working on :')
print (objects)
def SecondActionButton(self):
print ('Second Action working on :')
print (objects)
Your MyWidget
class would then look like:
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
uiFilePath = os.path.join(os.path.dirname(__file__),"myfile.ui")
self.ui = uic.loadUi(uiFilePath, self)
list_of_buttons = [self.ui.buttonA, self.ui.buttonB,...]
self.adaptors = []
for button in list_of_buttons:
self.adapters.append(MyButton(button))
For option 2, you'll want to change your class to be like this:
class MyButton(QtGui.QPushButton):
def __init__(self, *args, **kwargs):
QPushButton.__init__(self,*args,**kwargs)
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.buttonMenu)
self.clicked.connect(self.on_button_released)
# same code follows as in above class example
If widget promotion is done correctly, you won't need to do anything special in the __init__
method of the MyWidget
class as your custom class will be instantiated automatically when you call uic.loadUI
.