11

I have this simple problem, I can grab the event of a click on button, but now I need to handle a click over a widget, here is part of the code:

self.widget = QtGui.QWidget(self)
self.widget.setStyleSheet("QWidget { background-color: %s }" % color.name())
self.widget.setGeometry(150, 22, 50, 50)
self.connect(???)  <-- here

What should I put in the "???" to grab a click action over the created widget?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Lopoc
  • 1,308
  • 5
  • 16
  • 26

2 Answers2

21

you can try this i found this from this blog site's comment box from Jared Glass It was working fine for me

self.widget.mouseReleaseEvent=self.myfunction

or

self.widget.mouseReleaseEvent=lambda event:print 'working'

or

self.widget.mouseReleaseEvent=lambda event,my_variable:self.myfunction(event,my_variable)

only the last example is what i have written on my own rest all have been mentioned in http://popdevelop.com/2010/05/an-example-on-how-to-make-qlabel-clickable/ . The last code helps you to pass any variables eg:widget name or widget number if multiple widgets exists.

Ja8zyjits
  • 1,433
  • 16
  • 31
  • This is awesome! Works like a dream. – Darren Haynes Jun 02 '17 at 04:24
  • @Ja8zyjits The last one does not seem to work for me. I think the `mouseReleaseEvent` by default just passes the event. Do you think I will have to override the widget's `mouseReleaseEvent` to pass the extra argument? In its current form it says `TypeError: () missing 1 required positional argument: 'my_variable' ` – Tanvir Aug 07 '18 at 04:37
  • 1
    @Tanvir, I believe we are assigning a new definition to the `mouseReleaseEvent` here, and we are passing the required variables. This is done while registering the event. – Ja8zyjits Aug 07 '18 at 09:48
  • @Ja8zyjits is there another way to send a var? – raphiel May 25 '21 at 17:31
8

Use mousePressEvent instead.

import sys

from PyQt4.QtGui import QWidget, QApplication

class MyWidget(QWidget):
    def mousePressEvent(self, event):
        print "clicked"

app = QApplication(sys.argv)

widget = MyWidget()
widget.show()

app.exec_()
Jesse Aldridge
  • 7,991
  • 9
  • 48
  • 75