Qt World Summit: Register Today!

Signals and Slot using Functor

  • Hi ,

    Can anyone explain what is going on this code. How does the Functor class acts as a Slot ?

    Sorry for such a dumb question , Newbie to C++ and Qt.

    class Functor {
    Functor(Object *object, const QString &str) :
         m_object(object), m_str(str) {}
         void operator()(int x, int y) const {
         m_object->set(x, y, m_str);
       Object *m_object;
        QString m_str;
        connect(obj1, SIGNAL(coordChanged(int, int)),
        Functor("Some Text"));


  • @TopNotch_Mach07 said in Signals and Slot using Functor:

    How does the Functor class acts as a Slot ?

    it's because your connect statement connects to a function of signature (int x, int y) and the class has an operator() of the same signature.

  • see https://wiki.qt.io/New_Signal_Slot_Syntax

    New: connecting to simple function
    The new syntax can even connect to functions, not just QObjects

    in this case the operator() of the object is treated as a function

  • Your Functor class is not a functor !
    The constructor should only set parameter for the functor function. You must define a functor function in your class.

    Class Functor
    Returntype operator()(Argumentlist) { .....; return ....; }

    Functor f(ConstructorArguments);
    auto x=f(FunctorArguments); // here the syntax is like a normal function call

  • Lifetime Qt Champion

    If you are new to to c++
    Might be good to know the what functor really means.

    TLDR: Its basically just a function inside a class.
    We pass the class to other class where they expect a function pointer/adress but the magic of "operator ()"
    makes it work as otherwise it would complain about types.

Log in to reply