Question

i wanna inherit QLabel to add there click event processing. I'm trying this code:

class NewLabel(QtGui.QLabel):
    def __init__(self, parent):
        QtGui.QLabel.__init__(self, parent)

    def clickEvent(self, event):
        print 'Label clicked!'

But after clicking I have no line 'Label clicked!'

EDIT:

Okay, now I'm using not 'clickEvent' but 'mousePressEvent'. And I still have a question. How can i know what exactly label was clicked? For example, i have 2 edit box and 2 labels. Labels content are pixmaps. So there aren't any text in labels, so i can't discern difference between labels. How can i do that?

EDIT2: I made this code:

class NewLabel(QtGui.QLabel):
    def __init__(self, firstLabel):
        QtGui.QLabel.__init__(self, firstLabel)

    def mousePressEvent(self, event):
        print 'Clicked'
        #myLabel = self.sender()  # None =)
        self.emit(QtCore.SIGNAL('clicked()'), "Label pressed")

In another class:

self.FirstLang = NewLabel(Form)
QtCore.QObject.connect(self.FirstLang, QtCore.SIGNAL('clicked()'), self.labelPressed)

Slot in the same class:

def labelPressed(self):
    print 'in labelPressed'
    print self.sender()

But there isn't sender object in self. What i did wrong?

Was it helpful?

Solution

Answering your second question, I'll continue based on @gnud example:

  • subclass QLabel, override mouseReleaseEvent and add a signal to the class, let's call it clicked.
  • check which button was clicked in mouseReleaseEvent, if it's the left one emit the clicked signal.
  • connect a slot to your labels clicked signal and use sender() inside to know which QLabel was clicked.

OTHER TIPS

There is no function clickEvent in QWidget/QLabel. You could connect that function to a Qt signal, or you could do:

class NewLabel(QtGui.QLabel):
    def __init__(self, parent=None):
        QtGui.QLabel.__init__(self, parent)
        self.setText('Lorem Ipsum')

    def mouseReleaseEvent(self, event):
        print 'Label clicked!'

The answer from the PyQt Wiki works very well but I would add that the clickable class should call widget.mouseReleaseEvent (right before return True), just in case the user has customized this event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top