[Interest] How to pass parameter from Menu/Action to SLOT()

David M. Cotter dave at kjams.com
Tue Jan 5 22:09:47 CET 2021


in your handler you can call this:
> QAction	*actionP(qobject_cast<QAction *>(QObject::sender()));


and you'll get the action that caused the sending.
you can have previously stuffed something interesting into the objectName of the action, then recover it in your handler

does that make sense?

> On Jan 5, 2021, at 12:58 PM, Nicholas Yue <yue.nicholas at gmail.com> wrote:
> 
> Hi,
> 
>   I am programmatically generating a menu, each menu item has a unique name/label
> 
>   How can I determine which of the generated menu was clicked ?
> 
> ```
> void MainWindow::init()
> {
> :
> :
> QMenu *specialists = menuBar()->addMenu("&Specialists");
> if (!_engine.getSpecialistsManager().registeredSpecialists().empty()){
> 
> std::vector<QAction*> specialistMenuAction(_engine.getSpecialistsManager().registeredSpecialists().size());
> 
> size_t specialistMenuActionIndex = 0;
> for (auto iter = _engine.getSpecialistsManager().registeredSpecialists().begin();
> iter != _engine.getSpecialistsManager().registeredSpecialists().end();
> ++iter,specialistMenuActionIndex++)
> {
>            specialistMenuAction[specialistMenuActionIndex] = new QAction((boost::format("&%1%")%(iter->first)).str().c_str(), this);
>            specialists->addAction(specialistMenuAction[specialistMenuActionIndex]);
>            connect(specialistMenuAction[specialistMenuActionIndex], SIGNAL(triggered()), this, SLOT(specialistMenuHandler()));
> }
> }
> :
> :
> }
> ```
> 
> ```
> void MainWindow::specialistMenuHandler()
> {
>   std::cout << "MainWindow::specialistMenuHandler()" << std::endl;
> }
> ```
> 
> Cheers
> -- 
> Nicholas Yue

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20210105/cadcefb8/attachment.html>


More information about the Interest mailing list