Supply my own parameter (different from the Signal) to the Slot

  • I would like to supply my own parameter (different from the Signal) to the Slot. I know this code doesn't work, but perhaps it illustrates the idea of what I am trying to accomplish.

    @QAction* a;
    a = new QAction(this);
    connect(action, SIGNAL(triggered()), this, SLOT(setFoo(1.0f)));
    a = new QAction(this);
    connect(action, SIGNAL(triggered()), this, SLOT(setFoo(2.0f)));@

    Is this possible, or what would you have done when faced with similar problem?

  • QSignalMapper could be the solution to your problem:

    QAction* a1 = new QAction(this);
    QAction* a2 = new QAction(this);

    QSignalMapper* mapper = new QSignalMapper(this);

    mapper->setMapping(a1, 1);
    mapper->setMapping(a2, 2);

    connect(a1, SIGNAL(triggered()), mapper, SLOT(map()));
    connect(a2, SIGNAL(triggered()), mapper, SLOT(map()));

    connect(mapper, SIGNAL(mapped(int)), this, SLOT(setFoo(int)));

    QSignalMapper allows you to map QObject instances to integer, string and qobject pointers.
    An explicit mapping to float or double is not possible, but that can be worked around.

  • Moderators

    [quote author="Adelost" date="1367049667"]I would like to supply my own parameter (different from the Signal) to the Slot.[/quote]

    this is only possible in Qt5 and with a C++11 compatible compiler (also you need to have C++11 support configured Qt). See "here":
    Keyword: "c++11 lambda expressions"

  • I assumed the use of Qt 4 from the connection syntax in your code passage. In Qt5 with C++11 you can use the mentioned lambda expressions as well as std::bind:

    #include <functional>
    // ...

    // std::bind
    std::function<void()> f1 = std::bind(&MyClass::mySlot, this, 5.0);
    connect(this, &MyClass::mySignal, f1);

    // lambda expression
    std::function<void()> f2 = this { mySlot(5.0); };
    connect(this, &MyClass::mySignal, f2);

  • Thanks! The QSignalMapper worked quite well for my usage.

  • Either that, or just create a simple wrapper with another slot inside of which you emit the signal with the desired parameter. I guess QSM does the same thing internally. The C++11 lambda solution is the same concept, only instead of a named slot an unnamed function is used.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.