简体   繁体   English

使用部分函数传递值

[英]Passing values using partial functions

I am using a partial function to pass a value to a function argument, on a click of a QPushButton. 单击QPushButton时,我正在使用部分函数将值传递给函数参数。

self.SearchButton1 = QPushButton("Search")
self.SearchStudent1 = QLineEdit()

Below is how it is connected: 下面是它的连接方式:

self.connect(self.SearchButton1, SIGNAL("clicked()"),
             partial(self.Searching, self.SearchStudent1.text()))

The called function is as below: 调用的函数如下:

def Searching(self, num):
    print self.SearchStudent1.text()
    print num

I am not sure why num is not getting printed, whereas self.SearchStudent1.text() gets printed correctly on the press of the 'Search' button. 我不确定为什么不打印num ,而self.SearchStudent1.text()可以在按下“搜索”按钮时正确打印。

Please suggest if I am missing anything. 请建议我是否有任何遗漏。

EDIT : 编辑

I can anyhow pass the QLineEdit object using partial function and work with it: 我可以使用部分函数传递QLineEdit对象并使用它:

self.connect(self.SearchButton1, SIGNAL("clicked()"),
             partial(self.Searching, self.SearchStudent1))

def Searching(self, num):
    print self.SearchStudent1.text()
    print num.text() # works fine

The partial function will cache the arguments passed to it. 部分函数将缓存传递给它的参数。 So if the line-edit is empty when the signal is connected, an empty string will always be sent to the called method. 因此,如果在连接信号时line-edit为空,则始终将空字符串发送给被调用的方法。 (It's always a good idea to use repr when debugging with print , so that you can easily see output values like "" or None ). (在使用print进行调试时,最好使用repr ,这样您就可以轻松看到""None等输出值)。

If you want the current text is be sent to the slot when the button is clicked, you can use a lambda function, like this: 如果希望在单击按钮时将当前文本发送到插槽,则可以使用lambda函数,如下所示:

self.connect(self.SearchButton1, SIGNAL("clicked()"),
             lambda: self.Searching(self.SearchStudent1.text())

Or more simply: 或更简单地说:

self.SearchButton1.clicked.connect(
    lambda: self.Searching(self.SearchStudent1.text())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM