在 pyqt5 中单击按钮之前浏览按钮方法三重奏



我在 UI 中有浏览按钮,单击它应该触发打开文件对话框。我的问题是打开文件对话框甚至在单击浏览按钮之前就触发了。下面是我的代码

class GisedifySupportDialog(QtWidgets.QDialog, FORM_CLASS):
def __init__(self, parent=None):
"""Constructor."""
super(GisedifySupportDialog, self).__init__(parent)
self.setupUi(self)
self.img_upload=Upload_Image()
self.img_upload.setupUi(self.upload_image_dialog)
self.img_upload.pushButton.clicked.connect(self.browseTheFileAudio(self.img_upload.lineEdit))
def browseTheFileAudio(self,lineedit_name):
self.fileName = QtWidgets.QFileDialog.getOpenFileName(self, "Browse for the file", os.getenv("HOME"))
self.fileName=self.fileName
lineedit_name.setText(str(self.fileName))
return self.fileName

为什么briwseTheFileAudio 功能甚至在单击按钮之前就已经启动了?

当你说:

self.img_upload.pushButton.clicked.connect(self.browseTheFileAudio(self.img_upload.lineEdit))

您正在调用函数browseTheFileAudio,并且该函数的返回值将传递给pushButton.clicked.connect。那不是你想要的。您希望将函数对象(而不实际调用它(传递给pushButton.clicked.connect,您希望仅在单击按钮时触发。这就是绑定回调的方式。

看到您的回调也需要参数,您可以使用 lambda:

self.img_upload.pushButton.clicked.connect(lambda le=self.img_upload.lineEdit: self.browseTheFileAudio(le))

最新更新