我会继承QPushButton
并定义我自己的发送者和插槽。这个QObject.sender()
方法很诱人,但它给了我heebie-jeebies。
class MyPushButton(QPushButton):
def __init__(self, text = '', parent = None):
QPushButton.__init__(self, text, parent)
self.clicked.connect(self._handle_click)
my_click = QtCore.pyqtSignal(QObject)
def _handle_click(self):
my_click.emit(self)
def btnclick(btn):
print 'Handle button %s' % btn
for i in xrange(20):
btn = MyPushButton('%s %s' % ('Button', i + 1), self)
btn.my_click.connect(btnclick)
一种更 Pythonic 的方式可以定义类中的行为,如下所示:
class MyPushButton(QPushButton):
def __init__(self, button_number, parent = None):
QPushButton.__init__(self, '%s %s' % ('Button', button_number), parent)
self.button_number = button_number
self.clicked.connect(self._handle_click)
def _handle_click(self):
print 'Handle button %s' % self
for i in xrange(20):
btn = MyPushButton(i + 1, self)