将参数传递给 QWidget.mousePressEvent
Pass argument to QWidget.mousePressEvent
我正在覆盖 QWidget.mousePressEvent 这样的:
widget = QtWidgets.QWidget()
widget.mousePressEvent = my_function
def my_function(QMouseEvent):
print('Mouse Pressed')
但我的问题是,我现在如何将变量传递给它?我需要这样的东西:
for index in range(10):
widget = QtWidgets.QWidget()
widget.mousePressEvent = my_function(index)
def my_function(QMouseEvent, index):
print(index)
使用functools.partial
from functools import partial
def my_function(index, QMouseEvent):
print(index)
for index in range(10):
widget = QtWidgets.QWidget()
widget.mousePressEvent = partial(my_function, index)
或者使用 lambda
widget.mousePressEvent = lambda: event, index=index: my_function(index, event)
请注意,可选的 lambda 参数用于按值捕获索引。
我正在覆盖 QWidget.mousePressEvent 这样的:
widget = QtWidgets.QWidget()
widget.mousePressEvent = my_function
def my_function(QMouseEvent):
print('Mouse Pressed')
但我的问题是,我现在如何将变量传递给它?我需要这样的东西:
for index in range(10):
widget = QtWidgets.QWidget()
widget.mousePressEvent = my_function(index)
def my_function(QMouseEvent, index):
print(index)
使用functools.partial
from functools import partial
def my_function(index, QMouseEvent):
print(index)
for index in range(10):
widget = QtWidgets.QWidget()
widget.mousePressEvent = partial(my_function, index)
或者使用 lambda
widget.mousePressEvent = lambda: event, index=index: my_function(index, event)
请注意,可选的 lambda 参数用于按值捕获索引。