Connect QML signal to C++11 lambda slot (Qt 5)

后端 未结 3 1981
夕颜
夕颜 2020-12-18 20:44

Connecting a QML signal to a regular C++ slot is easy:

// QML
Rectangle { signal foo(); }

// C++ old-style
QObject::connect(some_qml_container, SIGNAL(foo()         


        
3条回答
  •  执念已碎
    2020-12-18 21:25

    Instead of creating lambda functions on the fly to deal with different signals, you may want to consider using a QSignalMapper to intercept the signals and send them to a statically-defined slot with an argument dependent on the source. The behavior of the function would then depend entirely on the source of the original signal.

    The trade-off with QSignalMapper is that you gain information about the source of the signal, but you lose the original arguments. If you can't afford to lose the original arguments, or if you don't know the source of the signals (as is the case with QDBusConnection::connect() signals), then it doesn't really make sense to use a QSignalMapper.

    hyde's example would require a little more work, but would allow you to implement a better version of QSignalMapper where you can add information about the source signal to the arguments when connecting the signal to your slot function.

    QSignalMapper class reference: http://qt-project.org/doc/qt-5.0/qtcore/qsignalmapper.html
    Example: http://eli.thegreenplace.net/2011/07/09/passing-extra-arguments-to-qt-slots/

    Here is an example rippling a signal through a QSignalMapper instance connecting to a top ApplicationWindow instance with an objectName of "app_window":

    for (auto app_window: engine.rootObjects()) {
      if ("app_window" != app_window->objectName()) {
        continue;
      }
      auto signal_mapper = new QSignalMapper(&app);
    
      QObject::connect(
        app_window,
        SIGNAL(pressureTesterSetup()),
        signal_mapper,
        SLOT(map()));
    
      signal_mapper->setMapping(app_window, -1);
    
      QObject::connect(
        signal_mapper,
        // for next arg casting incantation, see http://stackoverflow.com/questions/28465862
        static_cast(&QSignalMapper::mapped),
        [](int /*ignored in this case*/) {
          FooSingleton::Inst().Bar();
        });
      break;
    }
    

提交回复
热议问题