Reputation: 301
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.
Upvotes: 2
Views: 1551
Reputation: 120798
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', './')
Upvotes: 2
Reputation: 1181
In Qt (sorry, not familiar w/ PyQt) there's a couple of things to think about:
First, your signal & slot must take the same arguments. So the above won't work. set_widget_text() must take no arguments, as clicked() does not.
You can always tell what QObject emitted a signal inside the slot by casting sender() to the appropriate class. In this case, in Qt it would be:
QPushButton* myButton = qobject_cast<QPushButton*>( sender() );
I'm not sure how the casting would work in PyQt, but there should be a similar solution. From there you should be able to figure out what dialog to open. if QPushButton::text() doesn't work, you can use a simple associative array to map a string to each button when you initialize the buttons.
HTH
Upvotes: 0