Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QAction with custom parameter

Tags:

c++

qt

I want to execute my slot with parameter when dynamically created QAction clicked, but I can't add my variables when creating QAction in QMenu, and default triggered() slot can't pass it.

To be more clear, I want to archieve something like this:

connect(someAction, SIGNAL( triggered(MyClass*) ), this, SLOT( execute(MyClass*) );

How I can get this? I tried to create custom QAction, but I don't know how to add it to QMenu - there is no function like addAction(QAction).

like image 467
aso Avatar asked Feb 21 '15 14:02

aso


2 Answers

You can store your parameter in the action itself as a QVariant using QAction::setData() function. For example:

QVariant v = qVariantFromValue((void *) yourClassObjPointer);
action->setData(v);

In the slot you will have to extract the pointer like:

void execute()
{
    QAction *act = qobject_cast<QAction *>(sender());
    QVariant v = act->data();
    YourClass yourPointer = (YourClass *) v.value<void *>();
}
like image 149
vahancho Avatar answered Oct 31 '22 14:10

vahancho


  1. Gather your dynamic QAction's in one QActionGroup using QAction::setActionGroup()

  2. Use QAction::setData() to store the custom data in each QAction.

  3. connect QActionData's signal triggered(QAction*) to some slot.

like image 33
Matt Avatar answered Oct 31 '22 14:10

Matt