【问题标题】:Browse button method trigerring before the button is clicked in pyqt5 [duplicate]在pyqt5中单击按钮之前触发浏览按钮方法[重复]
【发布时间】:2020-05-26 05:30:32
【问题描述】:

我在 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 函数在按钮被点击之前就被触发了?

【问题讨论】:

    标签: python python-3.x pyqt pyqt5


    【解决方案1】:

    当你说:

    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))
    

    【讨论】:

    • 关于如何访问传递给 lambda 文件的值的任何建议?因为我得到了 le 的布尔值
    • @User123 如果le 是布尔值,则意味着self.img_upload.lineEdit 是布尔值。确认您没有在代码中的其他位置意外地将该小部件引用替换为布尔值。
    猜你喜欢
    • 2021-03-02
    • 1970-01-01
    • 2012-04-24
    • 2015-02-04
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多