Calling a method before executing a slot



  • Hello,

    I would like to ask whether it is possible to perform a specific function before executing a slot? I mean a mechanism similar to "before triggers" found in SQL.

    Example:

    class TestA : public QObject
    {
         Q_OBJECT
    
    public slots:
         void slotOne();
         void slotTwo();
    
    private:
        bool ready;
        void beforeAnySlot()
        {
             if(ready)
                  //execute slot
             else
                  //reject
        }
    };
    

    I would like to skip this solution:

    void slotOne() 
    {
        if(!ready)
            return;
    }
    
    void slotTwo() 
    {
        if(!ready)
            return;
    }
    

    Regards
    Paul


  • Moderators

    No, there is no such mechanism. But you could connect the signals to the slots when ready becomes true and disconnect when it becomes false.



  • Unfortunately I can not use this solution, because I want to use QWebChannel.


  • Qt Champions 2016

    hi
    Could you not call a function from the slots that
    can check if ready before performing the "action" ?

    If you provide more info about your use case, we might get good ideas :)



  • Example code:

    class MyClass2 : public QObject
    {
        Q_OBJECT
    
    public slots:
        void logout()
        {
            //can call slot only if user is logged
        }
    
        void slot2()
        {
            //can call slot only if user is logged
        }
    
        //...
    
    private:
        bool logged;
    }
    
    class Client : public QObject
    {
       Q_OBJECT
    
    public:   
    
       Client() 
       {
           channel.registerObject("dashboard", myClass);
           channel.registerObject("user", myClass2);
           //...
       }
    
       QWebChannel channel;
       QWebSocket socket;
       MyClass myClass;
       MyClass2 myClass2;
    }
    

    I want to avoid a situation where the client-side method 'logout' is called when the user is offline.

    //client.js
    
    //...
    channel.objects.user.logout();
    

    By limiting Web Channel can not register the object 'user' at the moment when the client logs in. Because the objects must be registered before initialize the client.
    "Note: A current limitation is that objects must be registered before any client is initialized."


  • Qt Champions 2016

    Ok. i see.

    who will call the slots?

    Could the signals go to same slot and you use the
    sender() to know whom send
    the signal?
    That way u need only check once.


  • Moderators

    @fmope You should always check whether the user is logged on or not in logout()! It is similar to the rule: check input parameters before using them and don't expect them to be always correct.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.