QAction with custom parameter

I want to execute my slot with a parameter when dynamically creating a QAction, but I cannot add my variables when creating a QAction in QMenu, and the default slot triggered() cannot pass it.

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

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

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

+5
source share
2 answers

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

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

In the slot you need to extract the pointer, for example:

 void execute() { QAction *act = qobject_cast<QAction *>(sender()); QVariant v = act->data(); YourClass yourPointer = (YourClass *) v.value<void *>(); } 
+7
source
  • Collect dynamic QAction into one QActionGroup using QAction::setActionGroup()

  • Use QAction::setData() to store user data in each QAction .

  • connect QActionData triggered(QAction*) signal triggered(QAction*) to slot .

+1
source

Source: https://habr.com/ru/post/1213863/


All Articles