Reputation: 12416
Is there a way curry qt slot? Maybe there is something similar to curryng?
Upvotes: 6
Views: 1185
Reputation: 14714
Of course, now we have Qt 5 and the ability to connect signals to arbitrary callable objects:
connect(sender, &MyClass::mySignal, receiver, std::bind(&OtherClass::mySlot, boundArg));
connect(sender, &MyClass::mySignal, receiver, [=] { receiver->mySlot(boundArg); });
Upvotes: 0
Reputation: 2022
You could use QSignalMapper to bind connect some signals to it and then connect it's own signals to target slots with some parameters attached.
// connect signal to mapper
signalMapper = new QSignalMapper(this);
signalMapper->setMapping(button1, QString("param1"));
signalMapper->setMapping(button2, QString("param2"));
connect(button1, SIGNAL(clicked()), signalMapper, SLOT(map()));
connect(button2, SIGNAL(clicked()), signalMapper, SLOT(map()));
// connect mapper signal to slot
connect(signalMapper, SIGNAL(mapped(const QString &)), this, SLOT(originalSlot(const QString &)));
Upvotes: 1
Reputation: 46479
Although it's not possible directly using Qt, some binding/currying is available through LibQxt. For example and from the docs of QxtBoundFunction:
By far, the most common expected use is to provide a parameter to a slot when the signal doesn't have offer one. Many developers new to Qt try to write code like this: \code connect(button, SIGNAL(clicked()), lineEdit, SLOT(setText("Hello, world"))); \endcode Experienced Qt developers will immediately spot the flaw here. The typical solution is to create a short, one-line wrapper slot that invokes the desired function. Some clever developers may even use QSignalMapper to handle slots that only need one int or QString parameter.
QxtBoundFunction enables the previous connect statement to be written like this: \code connect(button, SIGNAL(clicked()), QxtMetaObject::bind(lineEdit, SLOT(setText(QString)), Q_ARG(QString, "Hello, world!"))); \code This accomplishes the same result without having to create a new slot, or worse, an entire object, just to pass a constant value.
Additionally, through the use of the QXT_BIND macro, parameters from the signal can be rearranged, skipped, or passed alongside constant arguments provided with the Q_ARG macro. This can be used to provide stateful callbacks to a generic function, for example.
Many kinds of functions can be bound. The most common binding applies to Qt signals and slots, but standard C/C++ functions can be bound as well. Future development may add the ability to bind to C++ member functions, and developers can make custom QxtBoundFunction subclasses for even more flexibility if necessary.
Although I have submitted some patches to LibQxt, I haven't used this directly so your mileage may vary.
Upvotes: 4
Reputation: 25155
Binding arguments is not possible using Qt signal/slots. You'll have to use boost::signals and boost::bind instead to achieve such functionality.
Upvotes: 2