Hannah Hannah - 1 month ago 15
Python Question

mouseReleaseEvent triggers at application start, not on click in PyQt5

Inside of a Python 3.5 app written using PyQt5 I have mouseReleaseEvents like so

self.scene1.mouseReleaseEvent = self.setScene("1")


When they have variables to pass, they all trigger when the application starts, and they don't trigger when actually clicked.

However, if I remove the variable, they work when pressed, and they don't trigger at application start:

self.scene1.mouseReleaseEvent = self.setScene


But I have to get a variable over to this function

def setScene(self, scene):
print(scene)


Any suggestions as to why the variable causes this behavior and how to fix it?

Answer

Probably in every GUI when you bind function to event you have to use function name - it means without () and arguments.

You can have two method

  • "boring": create function without arguments and assign to event

    def new_fun(self):
        self.setScene("1")
    
    self.scene1.mouseReleaseEvent = self.new_fun
    
  • "popular": use lambda to create anonymouse function

    self.scene1.mouseReleaseEvent = lambda:self.setScene("1")
    

I don't know but mouseReleaseEvent may run function with event object which has information about event so you have to grab it

self.scene1.mouseReleaseEvent = lambda event:self.setScene("1")

If you have to use lambda in for x loop and use x in lambda function then you need

for x in some_list:
   self.scene1.mouseReleaseEvent = lambda event, arg=x :self.setScene(arg)

because lambda is "lazy" and it doesn't copy value from x to function when you define lambda but it gets value from x when you release mouse - but at that momen x has last value from some_list.

Comments