How to simulate a message bus in Qt?
I need to implement a simple message bus:
- One process only thus no need do D-Bus.
- Publish/subscribe to typed events (Could even be QObjects)
I was thinking of using QSignalMapper to tag the "named events", then re-emitting from a slot or connecting the publishers signal to the subscribe开发者_运维百科r's signal...
Any suggestions thoughts? Or should I go for the relatively simple design pattern?
PS: AFAICS for D-Bus on windows you need to install "3rd party" software to get it going with Qt.
Why don't you just use one dedicated QObject subclass as a message bus? There you define all signals hat might be exchanged over the message bus and you provide corresponding notify 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 generic method use the same approach as before. However, the (singleton) QObject subclass now only has a "message(QByteArray)" signal and a "sendMessage(QByteArray)" public method which emits this signal. You might want to declare the send message method as being a slot, too, just in case you want to connect another signal to the send method.
I use these approaches myself and they work perfecty fine. Even different threads can communicate 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 all message receivers get their own copy of messages with all the benefits you get if you do parallel calculations.
You can try this. It is excatly what you want. It is light-weighted 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;
}
精彩评论