How to pass a QString to a Qt slot from a QMenu via QSignalMapper or otherwise

前端 未结 1 1104
耶瑟儿~
耶瑟儿~ 2021-01-18 11:13

I have a QMenu with many submenus. These are dynamically created i.e. the names menus come from a db and created in a loop. Now i wanted to fire the same slot triggered() or

相关标签:
1条回答
  • 2021-01-18 11:59

    After adding the QAction to the menu, you only have to connect QMenu to the slot. You don't connect each action individually to the slot:

    for(int j=0; j<channelTypes[i].getNumChannels() ; j++){
        ch_name = <name from the database for the channel j>;
        QAction *subMenuAct = subMenu->addAction(tr(ch_name));
        subMenuAct->setData(ch_name);
    }
    
    connect(subMenu, SIGNAL(triggered(QAction *)), 
            this, SLOT(playChannel(QAction *)), Qt::UniqueConnection);
    

    As I don't know how you if you delete subMenu each time the dynamic menu is filled, the Qt::UniqueConnection ensure that the slot won't be reconnected multiple times.


    For the signal mapper version, you should only connect the actions to the mapper in the loop. The connection from the mapper to the slot should only be done once.

    for(int j=0; j<channelTypes[i].getNumChannels() ; j++){
       ch_name = <name from the database for the channel j>;
       QAction *subMenuAct = subMenu->addAction(tr(ch_name));
       connect(subMenuAct, SIGNAL(triggered()), signalMapper, SLOT(map()));
       signalMapper->setMapping(subMenuAct, ch_name);   
    }
    connect(signalMapper, SIGNAL(mapped(QString)), this, SLOT(playChannel(QString)));
    

    And for that case, the slot playChannel should accept a QString instead of a QAction*.

    0 讨论(0)
提交回复
热议问题