Friday, May 11, 2018

Signals and Slots

I'm going to start here, not because it's the first thing you need to know, but because I just lost most of a day getting bitten by Qt Creator's inconsistencies in this area.

On the surface I don't really see how signals and slots are significantly different that traditional callback functions, though the Qt docs claim they are better. Any time you start adding a language extension and another pre-compiler, I question the design. In this case I probably question the design of Qt and C++ equally.

Menus are special in Qt Creator. Instead of dragging and dropping components like you do for other things, they have a special editor right in the menubar and menus to let you add items and separators. When you create a menu item, you are actually creating a QAction that shows up in a special Action Editor window. If you right click on an action and select "Go to slot...", a helpful dialog will be displayed where you can pick the slot you are interested. Triggered is the default and most likely what you want. When you hit OK, a function and it's prototype are automatically created for you. This is very handy. I thought this also created some invisible link between the menu item and the function, but it does not. The link is simply the function name which must be of the form:
on_<widget name>_<signal name> ();
That's it, just name your function correctly, and the moc pre-pre-processor will connect it like magic.

Now here's where it gets weird, there is a special signal connection mode where you draw lines from one widget to another. If you are doing something simple like connecting a slider to a text box to display the value, it's great, you don't even have to write code. But if you need to actually write code to handle the signal, it gets a little confusing.

You can connect a signal to your window which looks like a ground connection on an electronics schematic. A dialog comes up that is similar to the "Go to slot..." one for menus. It lets you pick the signal to connect and you can define a new slot for it to connect to. I expected this to create the prototype and definition for the new slot automatically, but it does not. It really seems like a total waste of time, since you can just use the magical naming convention and not have to do anything in the UI.

No comments:

Post a Comment