PDA

View Full Version : How to get sender in static SLOT



qtplus
25th August 2017, 14:26
We can define static slots .


QMenu* getMenu(){
QMenu* menu = new QMenu;
auto action = menu->addAction("edit");

QObject::connect(action,&QAction::triggered,onClicked);

return menu;
}

Q_SLOT static void onClicked(){
throw;
}

Just I wonder that how to get whos the sender ? Is there a direct way to get it ?

jimbo
26th August 2017, 22:10
Hello,

In your slot:-

QObject *senderObj = sender();
if (senderObj == WHATEVER) {
//code
}
You should be able to manipulate senderObj, I don't know if this works in static slots.

Regards

d_stranz
27th August 2017, 22:23
I don't know if this works in static slots.

Almost certainly not. QObject::sender() is a protected, non-static method of the QObject class, so the only way you can call it is from within a member function of a class derived from QObject. The only way to call a non-static member function is through an instance of the class, and since a static method in most cases is called without an instance, there is no way to call sender().


Just I wonder that how to get whos the sender ? Is there a direct way to get it ?

I don't think so. In this case, the slot is nothing more than an ordinary function so there is no way in C++ that I know of to determine who is calling the function when you are inside it.

wysota
28th August 2017, 10:03
I'd say that it doesn't make that much sense to have a static slot like that. You can instead use a lambda expression as a slot where the sender can be accessed directly.

d_stranz
28th August 2017, 18:10
You can instead use a lambda expression as a slot where the sender can be accessed directly.

Interesting. Are lambda expressions treated as if they were inline member functions of the class in which they are declared? Or are you suggesting that the pointer to the sender be given as one of the scope arguments to the lambda?

wysota
29th August 2017, 07:28
Yes, you need to pull in the relevant object into the closure.


QObject::connect(action,&QAction::triggered,[action]() { action->doSomething(); });