button.clicked.connect(), pass a nested function as parameter
-
Hi!
I'm working on some code which contains a QPushButton and a QLineEdit.
When the QPushButton is pressed, one function will get some text from an external program, and then another function will transcribe this file path into the QLineEdit widget. However, I'm having some trouble passing these nested functions as the 'button.clicked.connect()' parameter:Code snippet:
... class Tool(QtWidgets.QMainWindow): def __init__(self, win_id=None, parent=None): ... # the text box self.textBox = QtWidgets.QLineEdit() # the button self.button= QtWidgets.QPushButton() self.button.clicked.connect() # insert code here! ... def getExtText(self): """Get some text from an external program""" return ExtProgram.text def updateTextBox(self, str): """Update the editable text box." self.TXT_FileSelectedPath.setPlaceholderText(str) ...
I'd really prefer to keep these two functions separate because there are a bunch of other, similar use cases.
Regarding the button's click event, here's what I've tried. I'm unfamiliar with 'lambda' and 'partial', but I've gone through some tutorials and I think my syntax is correct.self.button.clicked.connect(self.updateTextBox(self.getExtText))
self.button.clicked.connect(lambda: self.updateTextBox(self.getExtText))
self.button.clicked.connect(partial(self.updateTextBox, self.getExtText))
If you have any advice, I'd really appreciate it. Thank you!
-
@EscapistGorilla
First one won't work. I don't know about Pythonpartial
s so can't comment on third one.Second one is usual approach with
lambda
for passing your own parameter to a slot. Butself.getExtText
is a reference to a function/callable, it does not actually callself.getExtText
. Start withself.button.clicked.connect(lambda: self.updateTextBox(self.getExtText()))
and come back if that does not do what you intended.
-
This worked, thank you!