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

Nicholas Yue yue.nicholas at gmail.com
Tue Jan 5 22:19:49 CET 2021


Thanks David. It works.

I ended up with this approach.

```

specialistMenuAction[specialistMenuActionIndex]->setData(QVariant(QString(iter->first.c_str())));
```

````
void MainWindow::specialistMenuHandler()
{
    QAction *actionP(qobject_cast<QAction *>(QObject::sender()));
    if (actionP) {
        QString label = actionP->data().toString();
        std::cout << boost::format("MainWindow::specialistMenuHandler()
label = '%1%'") % label.toStdString() << std::endl;
    }
}
```

On Tue, 5 Jan 2021 at 13:09, David M. Cotter <dave at kjams.com> wrote:

> 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
>
>
>

-- 
Nicholas Yue
Graphics - Arnold, Alembic, RenderMan, OpenGL, HDF5
Custom Dev - C++ porting, OSX, Linux, Windows
http://au.linkedin.com/in/nicholasyue
https://vimeo.com/channels/naiadtools
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20210105/8f389cfe/attachment.html>


More information about the Interest mailing list