I want to react to a mouse click on a QLabel.
To achieve this I have redefined the method mouseReleaseEvent of QLabel.
I want to pass two arguments to the slot:
- the QtGui.QMouseEvent
- an ID of the clicked QLabel
But I can only pass one parameter. Either QtGui.QMouseEvent or the ID.
The combination does not work.
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSignal
class ExtendedQLabel(QtGui.QLabel):
#labelClickSignal_1 = pyqtSignal(QtGui.QMouseEvent)
labelClickSignal_1 = pyqtSignal(QtGui.QMouseEvent, int)
labelClickSignal_2 = pyqtSignal()
def __init(self, parent):
QtGui.QLabel.__init__(self, parent)
# redefinition
def mouseReleaseEvent(self, event):
#self.labelClickSignal_1.emit(event)
self.labelClickSignal_1.emit(event, 0)
self.labelClickSignal_2.emit()
class Test(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.names = ['Test1', 'Test2', 'Test3']
self.centralWidget = QtGui.QWidget()
self.setCentralWidget(self.centralWidget)
self.grid = QtGui.QGridLayout(self.centralWidget)
row = 0
for name in self.names:
self.addLabel(name, row)
row = row + 1
def addLabel(self, name, row):
label = ExtendedQLabel(name)
# QtGui.QMouseEvent is automatically passed to the slot
label.labelClickSignal_1.connect(self.onLabelClicked_1)
# The row ID is passed to the slot
label.labelClickSignal_2.connect(lambda id = row:
self.onLabelClicked_2(id))
# *This does not work*
label.labelClickSignal_1.connect(lambda id = row:
self.onLabelClicked_3(QtGui.QMouseEvent, id))
self.grid.addWidget(label, row, 1)
row = row + 1
def onLabelClicked_1(self, event):
if event.button() == QtCore.Qt.RightButton:
print('right')
else:
print('left')
def onLabelClicked_2(self, id):
print('Label {0} clicked'.format(id))
def onLabelClicked_3(self, event, id):
# *This does not work*
if event.button() == QtCore.Qt.RightButton:
print('right {0}'.format(id))
else:
print('left {0}'.format(id))
def main():
app = QtGui.QApplication(sys.argv)
t = Test()
t.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Ok, since your code had several pieces that did not work I rewrote the important Parts to achieve what you want. Please Note that I use PySide and not PyQt. This means you have to change the importe Statements and the
Signal
back to PyQt Notation. The rest is explained in the code.OLD ANSWER You have to define your Signal to support your two arguments:
See here for additional information.
Example from the docs: