Il modo migliore per passare gli argomenti è quello di non passare affatto. È possibile utilizzare la natura dinamica di Python e impostare qualsiasi dato necessario come proprietà proprie sui widget stessi, ottenere il widget di destinazione nel gestore utilizzando self.sender()
e quindi ottenere le proprietà necessarie direttamente dal widget.
In questo esempio cinque pulsanti vengono creati e lo stato richiesto è impostato sul widget tasto come my_own_data
proprietà:
import sys
from PyQt4 import QtGui, QtCore
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.centralwidget = QtGui.QWidget()
self.vboxlayout = QtGui.QVBoxLayout()
for idx in range(5):
button = QtGui.QPushButton('button ' + str(idx), None)
button.my_own_data = str(idx) # <<< set your own property
button.clicked.connect(self.click_handler) # <<< no args needed
self.vboxlayout.addWidget(button)
self.centralwidget.setLayout(self.vboxlayout)
self.setCentralWidget(self.centralwidget)
self.show()
def click_handler(self, data=None):
if not data:
target = self.sender() # <<< get the event target, i.e. the button widget
data = target.my_own_data # <<< get your own property
QtGui.QMessageBox.information(self,
"you clicked me!",
"my index is {0}".format(data))
app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())
Questa risposta non sembra molto popolare. 'QSignalMapper' non è ampiamente utilizzato? – 101
@figs. Non so perché il PO abbia accettato questa risposta, dato che la soluzione più convenzionale 'lambda/parziale' era già stata data. C'è stato un tempo in cui 'QSignalMapper' è stato più utile, perché PyQt non ha sempre supportato l'uso di' lambda/partial' come slot - ma è stato tanto tempo fa.Al momento, però, non riesco a pensare a uno scenario in cui potrebbe essere più efficace (tranne che in C++, ovviamente). – ekhumoro