How to simulate a message bus in Qt?

I need to implement a simple message bus:

  • Only one process does not require D-Bus.
  • Post / subscribe to typed events (maybe even QObjects)

I was thinking about using QSignalMapper to label “named events,” then re-emitting from the slot or connecting the publishers signal to the caller’s signal ...

Any suggestions of thought? Or do I need to stick with a relatively simple design scheme?

PS: AFAICS for D-Bus on windows you need to install "third-party software" to get it with Qt.

+4
source share
2 answers

Why don't you just use one dedicated QObject subclass as the message bus? There you define all the signals that can be exchanged for the message bus, and you provide the appropriate notification methods that emit these signals. Now every component that wants to receive “messages” can connect to the signals of interest.

If you want a more general method to use the same approach as before. However, the subclass of the (singleton) QObject class now has only the message (QByteArray) signal and the sendMessage (QByteArray) public method that emits this signal. You might want to declare the method of sending the message as a slot, just in case you want to connect another signal to the sending method.

I use these approaches myself and they work great. Even different threads can interact with each other using this mechanism without any problems. If you use the QByteArray approach, you will get something similar to DBus. You serialize and deserialize your messages and automatically make sure that all message recipients receive their own copy of the messages with all the benefits that you get if you perform parallel computing.

+3
source

You can try this. This is what you want. It is lightweight and easy to use. https://github.com/lheric/libgitlevtbus

#include "gitlmodual.h" #include <QDebug> int main(int argc, char *argv[]) { GitlModual cModual; /// subscribe to an event by name ("I am a test event") cModual.subscribeToEvtByName("I am a test event", [](GitlEvent& rcEvt)->bool ///< lambda function as a callback { qDebug() << "Hello GitlEvtBus!"; return true; } ); GitlEvent cEvent("I am a test event"); ///< create an event cEvent.dispatch(); ///< dispatch /// output: "Hello GitlEvtBus!" return 0; } 
0
source

All Articles