tags:

views:

194

answers:

3

In a Qt application, I have a bunch of automatically-created QActions (menu items) that I add to a menu in the menu bar. Each opens a different file. I'd like to connect them all to the same slot so as to not write the same code many times. From that slot, though, how do I figure out which of the QActions was triggered?

(Example: In Cocoa I'd do this with the sender parameter in the action selector.)

Thanks!

+6  A: 

In Qt, you also have access to the sender: QObject::sender.

Intransigent Parsnip
Exactly - in your slot you can do something like this:QAction *pAction = qobject_cast<QAction*>(sender());
Thomi
+1  A: 

You have two options:

Lukáš Lalinský
Thanks! QObject::sender() looks like it sufficient for the case I asked about, but it's good to know about the more general QSignalMapper option.
Geoff
Further, you can use QObject::setProperty() on your QAction to pass additional per-item data into your slot.
Geoff
`QAction::setData` is probably better than `QObject::setProperty`.
Lukáš Lalinský
+3  A: 

I would connect to the QMenu's "triggered" signal, rather then each QAction. This gives you the QAction that was clicked as the first parameter.

void MyObject::menuSelection(QAction* action)
{
  qDebug() << "Triggered: " << action->text();
} 

void MyObject::showMenu(QPoint menuPos)
{
  QMenu menu;
  menu.addAction( "File A" );
  menu.addAction( "File B" );
  menu.addAction( "File C" );
  connect(&menu, SIGNAL(triggered(QAction*)), this, SLOT(menuSelection(QAction*)));
  menu.exec(menuPos);
}
Andy