Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Storing QAction and slot in a struct?



  • I want to create many QAction for my QMenu. And since QAction need to be attached with a signal/slot connection each, I want to first store the QAction and their slots in an array and then populate them in a for loop later.

    I use a struct to package QAction and slot into one object, then put each into an array

    // Actions are first declared in the header
    QAction * newAct;
    QAction * openAct;
    
    struct ActionSlotPack{
       QAction * pAction;
       // void * connectionSlot?
    }
    
    // storing them into an array
    ActionSlotPack actionSlots[] =
       {
           {newAct, slotNew()},
           {openAct, slotOpen()}
       }
    
    // populating the connection for actions
    for(ActionSlotPack & item : actionSlots)
    {
       connect(item.pAction, &QAction::triggered, this, &item.connectionSlot);
    }
    

    I don't know the syntax to store the slot in the struct and output them in a for loop.


  • Lifetime Qt Champion

    Hi
    Is all of them slotNew, slotOpen member of same class?

    Basically you want to store a function pointer to a member
    They all have same arguments i assume ?

    try with std::function
    https://stackoverflow.com/questions/20353210/usage-and-syntax-of-stdfunction

    or if you are a bit lazy, the SLOT function might work as its simply a char *
    but you are using the new connection syntax so better to try with real member pointer.

    Do note that this

    ActionSlotPack actionSlots[] =
       {
           {newAct, slotNew()},
           {openAct, slotOpen()}
       }
    

    cannot be global as the slots belongs to an object and we need an instance to grab pointer to it.
    like

    ActionSlotPack actionSlots[] =
       {
           {newAct, object->slotNew()},
           {openAct, object->slotOpen()}
       }
    


  • @mrjj

    Hi the slots can be a boolean or a void with no arguments.


  • Lifetime Qt Champion

    @lansing
    Ok
    Then its a more complicated.
    Maybe just use SLOT and old syntax for that connect unlike you feeling digging into templates and fun stuff?



  • @mrjj
    How do I use the SLOT one, I want the easy solution.


  • Lifetime Qt Champion

    @lansing
    Then its just to store a const char *

    struct ActionSlotPack {
       QAction * pAction;
       const char * connectionSlot;
    };
    
    ...
    ActionSlotPack actionSlots[] =
           {
               {newAct, SLOT(slotNew())},
               {openAct, SLOT(slotOpen())}
           };
    
    

Log in to reply