PDA

View Full Version : [PyQt4] Trouble with event handling



Dodle
4th May 2009, 06:01
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:

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:

button1 = QtGui.QPushButton("Button 1")
button2 = QtGui.QPushButton("Button 2")
button3 = QtGui.QPushButton("Button 3")

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

e8johan
4th May 2009, 08:58
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.

Dodle
4th May 2009, 20:28
I think that I am close:

#! /usr/bin/env python
"""
Mapping
"""

import sys
from PyQt4 import Qt

class MainWindow(Qt.QWidget):
def __init__(self):
Qt.QWidget.__init__(self)

button1 = Qt.QPushButton("Button 1")
button2 = Qt.QPushButton("Button 2")
button3 = Qt.QPushButton("Button 3")

self.button_mapper = Qt.QSignalMapper()

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 = Qt.QVBoxLayout(self)
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

app = Qt.QApplication(sys.argv)
frame = MainWindow()
frame.show()
sys.exit(app.exec_())

I just don't know how to get the label off of the button.

Dodle
4th May 2009, 20:35
Okay I figured out what to put in the line I was having trouble with before:

labelVal = eventVal.text()

But every button I press prints "Button 3". I guessing because it was the last item to be mapped.

Dodle
5th May 2009, 04:45
I got some help with this over at ubuntuforums.org:

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.