0

I'm searching for a way to have a kind of signal broadcast with Qt. In my design I got an Auth object that can be used inside c++ and qml side:

class Auth : public QObject
{
    Q_OBJECT
public:
    Auth() ;

    Q_INVOKABLE bool isLogged() const ;

    Q_INVOKABLE void reconnect() ;

    Q_INVOKABLE void login(QString mail, QString password) ;

    Q_INVOKABLE void logout() ;

protected:
    static QString token_ ;

signals:
    void error(QString message) ;
    void logged() ;
    void loggedOut() ;
};

When login is called then logged() signal is fired and loggedOut() signal for logout().

1- In the qml part i've got this code:

Auth {
    id: auth
    onError: console.log("auth error")
    onLogged: console.log("auth logged")
    onLoggedOut: console.log("auth logged out")
}

2- And in the c++ side I may do in some failure cases:

Auth auth ;
auth.logout() ;

The two Auth objects from 1 and 2 are not the same so the loggedOut emitted from one is not fired in the other, that's ok.

Now what I'm trying to do is to have a way to broadcast the loggedOut signal to every instances of Auth. I'd like to avoid to share a common instance of Auth between C++ and qml side.

Is there a standard way to do this?

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
Falco
  • 277
  • 5
  • 12

1 Answers1

0

I don't think so, since you're essentially looking for a Qt/C++ way of finding all instances of a particular class (Auth, in this case). See e.g., this or this.

Depending on lots of other factors, you could:

  • maintain a static list of all class instances within the Auth object and connect the different instances within Auth::Auth()
  • manually connect Auth::loggedOut() for the first Auth object to all other instances (note: be careful, if you get a circular connection you'll enter an infinite loop).
  • make Auth a singleton (though I'd consider that violating your "don't share an instance" stipulation)

There are probably other (maybe better) options too.

Community
  • 1
  • 1
eclarkso
  • 1,087
  • 9
  • 21
  • I implemented the first method. I was thinking to switch to the second but they are not strictly equivalent, it seems I would lose the ability to trigger an event to a peculiar instance. – Falco May 27 '16 at 08:54