mr-edd.co.uk :: horsing around with the C++ programming language

sigfwd

A complaint often made about Qt is that the signals/slots mechanism wasn't written in a type-safe manner. Surely there were reasons for this (poor support for C++ templates at the time, I suspect), but having to go through the trouble of adding lots of boilerplate code, coupling your classes to QObject and running an extra step in the build gets old pretty quickly.

sigfwd attempts to fix all that by allowing you to connect Qt signals directly to C++ functions and functors. No moc-ing, Q_OBJECT/slots/… macros or derivation from QObject required.

Recent activity

Code

Clone the repository using mercurial:

> hg clone http://bitbucket.org/edd/sigfwd

Or get a zip file of the code.

Quick start

#include <sigfwd/sigfwd.hpp>
#include <QtGui>
#include <iostream>

void show_value(int value)
{
    std::cout << "slider moved to " << value;
}

int main(int argc, char **argv)
{
    // Create a window containing a slider
    QApplication app(argc, argv);

    QWidget window;
    QHBoxLayout *layout = new QHBoxLayout(&window);

    QSlider *slider = new QSlider(Qt::Horizontal, &window);
    slider->setMinimum(0);
    slider->setMaximum(100);
    layout->addWidget(slider);

    // connect the slider to the show_value function
    sigfwd::connect(slider, SIGNAL(valueChanged(int)), show_value);

    // show the window
    window.show();
    return app.exec();
}

Qt signals can also be connected to functors such as those created by std::bind1st/bind2nd, std::ptr_fun, boost::bind, boost::signals, boost::signals2, boost::function and many more.

sigfwd checks the call signatures of the Qt signal and the functor to which it is being connected and will abort the connection attempt if they are incompatible.

Further reading

Comments

Kjell Hedström

[22/02/2011 at 10:33:56]

Nice! I like it. Have you told the "trolls" about it and did you get any feedback?

My only objection to using your code is that it's tightly connected to boost. Unfortunately, that makes it a "non-use" library for me in the "semi-embedded" world. But it seems it wouldn't be THAT much for to get rid of boost... If I get some time between projects that would be really fun to look into :)

Either way. Very nice! I hope the trolls (Nokia/Qt) becomes inspired!

Edd

[22/02/2011 at 19:17:39]

I haven't not notified/taunted the Trolls, no :)

I think if they were to adopt something like this, they might as well bite the bullet and re-implement their signals/slots with templates.

As for re-implementing it without boost, you're of course welcome to try, but re-doing the function_traits stuff would probably be a pain, I suspect.

(optional)
(optional)
(required, hint)

Links can be added like [this one -> http://www.mr-edd.co.uk], to my homepage.
Phrases and blocks of code can be enclosed in {{{triple braces}}}.
Any HTML markup will be escaped.