PyQt connect inside for loop vs. separate calls results in different behavior

后端 未结 1 1414
天命终不由人
天命终不由人 2020-12-11 12:53

I\'m building a plotting UI that lets a user generate multiple plots from loaded data sets. As part of this the user can add marker lines to their plots to examine (x, y) va

相关标签:
1条回答
  • 2020-12-11 13:10

    When you connect a signal to a lambda function, the contents of the lambda function are evaluated when the signal is emitted, not when the signal is connected. As such, the variables you use (marker_one and marker_two) always point to the objects created in the last iteration of the loop.

    One simple solution is to explicitly pass in marker_one and marker_two as default arguments to variables of the same name, in the signature of the lambda function:

    lambda marker_one=marker_one: self.update_marker_vals(marker_one, "Marker One")
    lambda marker_two=marker_two: self.update_marker_vals(marker_two, "Marker Two")
    

    There are several useful answers relating to a very similar problem here, specifically the answer by ekhumoro, if you would like to know more (my answer to that question my also be of use, although ekhumoro's solution is cleaner)

    0 讨论(0)
提交回复
热议问题