[PyQt4] Trouble with event handling
I am connecting widgets with event handlers in PyQt and trying to find the widget that was used. I learned to do this in wxPython:
Code:
button1 = wx.Button(self, -1, "Button 1")
button2 = wx.Button(self, -1, "Button 2")
button3 = wx.Button(self, -1, "Button 3")
button_group = (button1, button2, button3)
for entry in button_group:
entry.Bind(wx.EVT_BUTTON, self.onButton)
def onButton(self, event):
eventVal = event.GetEventObject()
labelVal = eventVal.GetLabel()
print "%s pressed" % labelVal
But I am having trouble figuring out how to do this with PyQt. This is the only way that I know how to catch events:
Code:
button_group = [button1, button2, button3]
for entry in button_group:
self.connect(entry, QtCore.SIGNAL('clicked()'), self.onButton)
def onButton(self):
"""
I do not know what to put here.
"""
pass
Re: [PyQt4] Trouble with event handling
There is the QObject::sender method that you can use. It is not really considered good style, instead, it would be better to use a QSignalMapper.
Re: [PyQt4] Trouble with event handling
I think that I am close:
Code:
#! /usr/bin/env python
"""
Mapping
"""
import sys
from PyQt4 import Qt
def __init__(self):
button_group = [button1, button2, button3]
for entry in button_group:
self.connect(entry, Qt.SIGNAL('clicked()'), self.onButton)
self.button_mapper.setMapping(entry, "blah")
sizer.addWidget(button1, 1)
sizer.addWidget(button2, 1)
sizer.addWidget(button3, 1)
def onButton(self):
eventVal = self.button_mapper.mapping("blah")
labelVal = eventVal."""What to put here"""()
print labelVal
frame = MainWindow()
frame.show()
sys.exit(app.exec_())
I just don't know how to get the label off of the button.
Re: [PyQt4] Trouble with event handling
Okay I figured out what to put in the line I was having trouble with before:
Code:
labelVal = eventVal.text()
But every button I press prints "Button 3". I guessing because it was the last item to be mapped.
Re: [PyQt4] Trouble with event handling
I got some help with this over at ubuntuforums.org:
Quote:
Originally Posted by regomodo
I believe you are looking for the objectname for a widget.
Say you have
a_button = QToolbutton() and have set it's objectName with
a_button.setObjectName("spam")
You have also slotted(not sure that's the right term) the button to a function like:
self.connect(a_button, SIGNAL("clicked()"), self.eggs)
The function to find the objectName of the button would look like this.
def eggs(self):
print self.sender().objectName()
Hope that's what you wanted.
I think that this method will work best for what I want to accomplish. Thanks for your help.