且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按下按钮时调用函数

更新时间:2023-12-02 23:13:58

Qt 信号可以有参数,这些参数将传递给它们所连接的插槽;一个例子是新值作为信号 changed 中的参数.因此,虽然您可以有一个带参数的槽,但您不能在将信号连接到槽时定义这些值的实际值,因为它们将在发出信号时定义.

Qt signals can have arguments that will be passed to the slots they are connected to; an example would be the new value as an argument in a signal changed. Therefore, while you can have a slot with arguments, you cannot define the actual values of those when connecting the signal to the slot, as they will be defined when emitting signal.

为了在连接时定义一个参数,你可以使用一个额外的函数,它只用定义的参数调用原始函数:

For defining an argument at connect time, you can use an additional function which does nothing but calling the original function with the defined argument:

def wrapper():
    funcion(12)

def funcion(a):
    print "Hola mundo" + str(a)

[...]
btn_brow_4.clicked.connect(wrapper)

附带说明:wrapper 在这里不使用大括号:该函数不被调用,只是作为参数传递给函数 connect.在你的代码中,你调用你的函数funcion,它什么都不返回(=None),它被传递给connect> 在您的原始代码中,导致您收到错误消息.

As a side note: wrapper does not use braces here: the function is not called, but simply passed as an argument to the function connect. In your code, you called your function funcion, which returns nothing (=None), which was passed to connect in your original code, resulting in the error message you received.

为了更简洁,您还可以使用匿名函数:

To make that a bit cleaner, you can also use an anonymous function:

btn_brow_4.clicked.connect(lambda: funcion(12))

请注意,Qt 也提供了执行此操作的方法,但(至少对我而言)Python 变体更易于阅读.

Note that Qt also provides ways of doing this, but (at least for me) the Python variants are easier to read.

更多信息:http://eli.thegreenplace.net/2011/04/25/passing-extra-arguments-to-pyqt-slot/