[英]Retrieving the sender of PyQt4 QLabel mousepressevent
I'm programming an interface in PyQt4 and I am using QLabels and making them clickable using the mousepressevent function. 我正在PyQt4中编程一个接口,并且正在使用QLabel,并使用mousepressevent函数使它们可单击。 I have multiple labels (signals) that have the same mousepressevent slot.
我有多个具有相同mousepressevent插槽的标签(信号)。 Here is the gist of what I'm trying to do.
这是我要做什么的要点。
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
lbl1=QtGui.QLabel(self)
lbl2=QtGui.QLabel(self)
lbl1.mousePressEvent=self.exampleMousePress
lbl2.mousePressEvent=self.exampleMousePress
def exampleMousePress(self,event):
print "The sender is: " + sender().text()
The problem is that the sender function is not working here. 问题是发件人功能在这里不起作用。 Is there a way to get the event sender in the exampleMousePress function?
有没有办法在exampleMousePress函数中获取事件发送者?
Thank you all! 谢谢你们!
You can use event-filtering to do this: 您可以使用事件过滤来执行此操作:
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
lbl1 = QtGui.QLabel(self)
lbl2 = QtGui.QLabel(self)
lbl1.installEventFilter(self)
lbl2.installEventFilter(self)
def eventFilter(self, source, event):
if event.type() == QtCore.QEvent.MouseButtonPress:
print "The sender is:", source.text()
return super(Example, self).eventFilter(source, event)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.