Qt: Connecting signals to … signals

September 16th, 2005

I found out today that Qt's slots/signals architecture is even better than I thought. Normally, developers connect widget signals to widget slots to be notified of events. Today I discovered that signals can actually be connected to other signals, which saved me from writing some really stupid code...

This may seem weird, but consider this scenario. You have a custom widget, called MyWidget, that has a signal, somethingClicked(), which is emitted when a user clicks, uh, something. But now you want to add a QPopupMenu as a right-click context menu, that causes the somethingClicked() signal to be emitted also. It turns out there's a hard way and an easy way to do this.

First, the hard way:

1. Add a new slot called emitSomethingClickedSlot() that looks like this:

CODE:
  1. MyWidget::emitSomethingClickedSlot() {
  2.         emit somethingClicked();
  3. }

2. Then, connect the QPopupMenu's menu item to this slot, like so:

CODE:
  1. popupMenu->insertItem( "Click me", this,
  2.      SLOT(emitSomethingClickedSlot()) );

That sucks. We just created a slot whose sole purpose is to turn around and emit a signal. What a waste of editor space. It would have been smarter to connect the menu item's signal directly to the somethingClicked() signal.

Here's the easy way:

CODE:
  1. popupMenu->insertItem( "Click me", this,
  2.      SIGNAL(somethingClicked()) );

Now that's concise. Sometimes it pays to connect signals to signals.

Leave a Reply