[Qt-interest] Convert to signal and slot

Ross Bencina rossb-lists at audiomulch.com
Fri Jul 22 05:06:18 CEST 2011


From: "William Gordon Rutherdale (rutherw)"
>> 21.07.2011, 21:42, "Sajjad" <dosto.walla at gmail.com>:
>> > Hello forum,I have a project where they have the observer pattern
>> implemented and i want to re-implement it using the Qt's signal and
>> slot mechanism.
>>
>> Are you sure you need it? You can freely use observer pattern with Qt.
>>
>
> In other words (for the benefit of the original poster), Qt already
> provides observer semantics.  That's what signal / slot / connect() is
> for.

I would ask are the original poster, are you sure signals/slots are the best
approach for what you're doing?

Signals and slots are not always the best option for implementing "The 
Observer Pattern" (whatever that is, it has many interpretations).

In my view, if you have a complex conduit of change (not just a single
"notify()" type event) you are better off defining an abstract listener type
and formalising the relationship between observer and observed, rather than
gluing things together with a bunch of signals.

Then instead of:

connect(...
connect(...
connect(...
connect(...
connect(...
connect(...

for all of the individual events you need (and often you need a lot of them,
as in Qt ModelView) you just subclass from a listener base class and say:

observed->addListener( this );

Of course the oposite is also true: if you have a single event, Qt's
connect() is much easier than subclassing a listener.

All approaches have their merits. Boost-style C++ template-based callback
adapters are another option if you don't want to get moc involved. I use
this for notifications in layers where I'm not prepared to interested in
introducing Qt dependencies.

Ross.




More information about the Qt-interest-old mailing list