Make QLabel clickable

Viewed 17172

I have a Qlabel filled with QPixmap and I want to start a process/function once this label clicked. I had extended QLabel class as follows:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QLabel_alterada(QLabel):
  clicked=pyqtSignal()
  def __init(self, parent):
    QLabel.__init__(self, QMouseEvent)

  def mousePressEvent(self, ev):
    self.clicked.emit()

Then, in my pyuic5-based .py file (I used QtDesigner to do the layout) after importing the module where I save the extended QLabel class, inside the automatically generated setupui, function I changed my Label from

self.label1=QtWidgets.QLabel(self.centralwidget)

to

self.label1 = QLABEL2.QLabel_alterada(self.centralwidget)

Finally, in the core app Python file where I put all the procedures/classes whetever needed to the application functionality I added

self.ui.label1.clicked.connect(self.dosomestuff) 

The application does not crashes but the labels still not clickable. Can someone give me some help on this?

3 Answers

Since Python can pass function as object, I think make a class inherit QLabel only to make it clickable is overkill. Instead I do like this:

import sys

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QFrame, QLabel


def foo(*arg, **kwargs):
   print("Bar")


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    Frame = QFrame()
    label = QLabel(Frame)
    label.mousePressEvent = foo
    label.setText("Label")
    Frame.show()
    sys.exit(app.exec_())
class ClickableLabel(QtWidgets.QLabel):
    def __init__(self, whenClicked, parent=None):
        QtWidgets.QLabel.__init__(self, parent)
        self._whenClicked = whenClicked

    def mouseReleaseEvent(self, event):
        self._whenClicked(event)

and then:

        my_label = ClickableLabel(self.my_label_clicked)
...
    def my_label_clicked(self, event):
        button = event.button()
        modifiers = event.modifiers()

        if modifiers == Qt.NoModifier and button == Qt.LeftButton:
            logger.debug('my_label_clicked: hooray!')
            return

        LOGGER.debug('my_label_clicked: unhandled %r', event)
Related