简体   繁体   中英

Passing PyQt QLineEdit text as parameter

I'm trying to edit a QLineEdit widget and then send the new text as a parameter to a function, but it's always returning the original text instead of the new text. Here's a snippet of the code

self.shortCoffee1Label = QLineEdit("0")
self.shortCoffee1Label.editingFinished.connect(self.sendValue(48, int(self.shortCoffee1Label.text())))

and then the sendValue function

    def sendValue(self, var, val):
        def emmitValue():
            self.messageReceived.setText("Sending new value...")
            print("var received: " + str(var))
            print("val received: " + str(val))
            self.thread.sendValue(var, val)
        return emmitValue

But val is always 0, which is the original value it was set to. What am I doing wrong?

If you do like that the program will store the value "0" and attach it to editingFinished instead of refreshing it every time you call the function. So you should use lambda (sorry for my bad English):

self.shortCoffee1Label = QLineEdit("0")
self.shortCoffee1Label.editingFinished.connect(lambda: self.sendValue(48, int(self.shortCoffee1Label.text())))

Got it.

Here's the final code:

self.shortCoffee1Label.editingFinished.connect(self.sendValue(48, self.shortCoffee1Label))

 def sendValue(self, var, val):
        def emmitValue():
            self.messageReceived.setText("Sending new value...")
            print("var received: " + str(var))
            print("val received: " + str(int(val.text())))
            self.thread.sendValue(var, int(val.text()))
        return emmitValue

So the idea was to send the object itself as the parameter so I could retrieve the updated text. As it turns out, it might be interpreting that as a "send the text that this object had at compile". By sending the object itself, the problem was resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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