Simplify signals and slots connections with unique connections in Qt 4.6

— richardwb on Tuesday, January 12, 2010 @ 14:43

Somehow there's absolutely no mention of this in the What's New in Qt 4.6 summary, but one of my favorite new features in Qt 4.6 is a surprisingly simple one: the Qt::UniqueConnection connection type.

The default connection type for connect() is Qt::AutoConnection, which sets up either a direct or queued connection depending on whether the signaling object and receiving slot are in the same thread or not. This connection type allows you to connect a particular signal/slot pair multiple times (so emitting a signal once could call a slot twice) which has caught me on a number of occasions.

This is really simple to work around: you can add some bookkeeping to keep track of that particular connection or you can use disconnect() where appropriate to maintain 0 or 1 connections. The new Qt::UniqueConnection connection type, on the other hand, lets you be sure that a connection is made only once. It's not something you always need, but when you do, it lets you keep your code a bit cleaner.

One caveat is that Qt::UniqueConnection makes a unique Qt::AutoConnection, meaning you don't have the ability to explicitly specify a unique queued connection, for example. In a case like that you will have to keep track of the connections yourself, as before.

comments powered by Disqus