views:

901

answers:

5

Hello, 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?

+1  A: 

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!'
gnud
+1  A: 

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.
Idan K
A: 

Here is a solution that does not require subclassing: http://www.unravellings.net/PyQtWiki/Making%20non-clickable%20widgets%20clickable

A: 

Hi, the above document seems to have moved to: http://diotavelli.net/PyQtWiki/Making%20non-clickable%20widgets%20clickable Regards

A: 

I wrote an example on how to extend QLabel as gnud posted earlier here: An example on how to make QLabel clickable. It might be a little to newbie centered for you experienced dudes.

MikaelHalen