开发者

Figuring out which menu item was triggered in Qt

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 sl开发者_如何转开发ot, 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!


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);
}


You have two options:

  • Call sender() in the slot, which will return the action that triggered the signal.
  • Use QSignalMapper.


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


As mention above, you have access to the emitter handle via QObject::sender(), which is a great feature in Qt (especially when dealing with n amounts of runtime, dynamically instanced objects of unknow type - perhaps defined in a settings file somewhere).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜