1

对不起,标题是满嘴巴,但基本上我在这里要做的是我有3个按钮,它们都打开QFileDialog供用户选择要使用的文件。由于动作相同,我想对所有 3 个使用相同的功能,但根据按下的按钮,我需要更新不同的 QLineEdit 以反映 GUI 中的文件路径。我该如何实现呢?

        #Create the prompt for user to load in the q script to use
        self.qFileTF = QtGui.QLineEdit("Choose the q script file to use")
        self.qFileButton = QtGui.QPushButton("Open")
        self.qFileButton.setFixedSize(100,27)
        self.fileLayout1.addWidget(self.qFileTF)
        self.fileLayout1.addWidget(self.qFileButton)

        #Create the prompt for user to load in the light house file to use
        self.lhFileTF = QtGui.QLineEdit("Choose the light house file to use")
        self.lhButton = QtGui.QPushButton("Open")
        self.lhButton.setFixedSize(100,27)
        self.fileLayout2.addWidget(self.lhFileTF)
        self.fileLayout2.addWidget(self.lhButton)

        #Create the prompt for user to choose to reference an older version of q script
        self.oldQCB = QtGui.QCheckBox("Reference an older version Q script")
        self.oldQTF = QtGui.QLineEdit("Choose the q script file to use")
        self.oldQTF.setEnabled(False)
        self.oldQButton = QtGui.QPushButton("Open")
        self.oldQButton.setEnabled(False)
        self.oldQButton.setFixedSize(100,27)
        self.fileLayout3.addWidget(self.oldQTF)
        self.fileLayout3.addWidget(self.oldQButton) 

        self.connect(self.qFileButton, QtCore.SIGNAL("clicked()"), self.loadFile)
        self.connect(self.lhButton, QtCore.SIGNAL("clicked()"), self.loadFile)
        self.connect(self.oldQButton, QtCore.SIGNAL("clicked()"), self.loadFile)

    def loadFile(self):     
        selFile = QtGui.QFileDialog.getOpenFileName()           

        if self.qFileButton:
            self.qFileTF.setText(selFile)
        elif self.lhFileTF:
            self.lhFileTF.setText(selFile)
        else:
            self.oldQTF.setText(selFile)    
4

2 回答 2

2

尝试使用以下sender方法:

def loadFile(self):
    selFile = QtGui.QFileDialog.getOpenFileName()
    if self.sender() == self.qFileButton:
        self.qFileTF.setText(selFile)
    elif self.sender() == self.lhFileTF:
        self.lhFileTF.setText(selFile)
    else:
        self.oldQTF.setText(selFile)      
于 2012-08-25T00:11:02.003 回答
1

您可以使用 lambda 函数(或函数)将QLineEditto change 作为附加参数传递给插槽:

    def loadFile(lineEdit):
        return lambda: self.loadFile(lineEdit)

    self.qFileButton.clicked.connect(loadFile(self.qFileTF))
    self.lhButton.clicked.connect(loadFile(self.lhFileTF))
    self.oldQButton.clicked.connect(loadFile(self.oldQTF))

def loadFile(self, lineEdit):     
    selFile = QtGui.QFileDialog.getOpenFileName()           
    lineEdit.setText(selFile)
于 2012-08-26T02:37:46.830 回答