Qt: Connecting signals to … signals
September 16th, 2005I 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:
-
MyWidget::emitSomethingClickedSlot() {
-
emit somethingClicked();
-
}
2. Then, connect the QPopupMenu's menu item to this slot, like so:
-
popupMenu->insertItem( "Click me", this,
-
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:
-
popupMenu->insertItem( "Click me", this,
-
SIGNAL(somethingClicked()) );
Now that's concise. Sometimes it pays to connect signals to signals.