Search code examples
pythonqtpyqt4signals-slots

pyqt: How to use a same function to set text of different qt widget?


I am new to both Qt and python. It may be a easy question to most of your guy, but I can't find it on Google. I have a form, with different sets of "path and button" combinations. click each path it would open a QFileDialog.getOpenFileName() dialog, and setText to the lineEdit.

My questions is how to write a function like this:

QtCore.QObject.connect(btn1, QtCore.SIGNAL("clicked()"), set_widge_text(lineEdit1))
QtCore.QObject.connect(btn2, QtCore.SIGNAL("clicked()"), set_widge_text(lineEdit2))
QtCore.QObject.connect(btn3, QtCore.SIGNAL("clicked()"), set_widge_text(lineEdit3))

in function:

def set_widge_text(self, widget_name)
      widget_name.setText("self.fname")

def open_file_dialog(self):
     fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file',
             './')
     self.fname = fname

Is there anyway to achieve this? I don't want to write different sets of set_widge_text() just for different lineEdits, any help would be appreciated.

Many thanks.


Solution

  • Connect the signals using a lambda:

        btn1.clicked.connect(lambda: self.set_file_name(lineEdit1))
        btn2.clicked.connect(lambda: self.set_file_name(lineEdit2))
        btn3.clicked.connect(lambda: self.set_file_name(lineEdit3))
    
    def set_file_name(self, edit):
        edit.setText(self.open_file_dialog())
    
    def open_file_dialog(self):
        return QtGui.QFileDialog.getOpenFileName(self, 'Open file', './')