WeakConnect.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #ifndef WEAKCONNECT_H
  2. #define WEAKCONNECT_H
  3. #include <type_traits>
  4. // Qt includes
  5. #include <QObject>
  6. template <typename Func1, typename Func2, typename std::enable_if_t<std::is_member_pointer<Func2>::value, int> = 0>
  7. static inline QMetaObject::Connection weakConnect(typename QtPrivate::FunctionPointer<Func1>::Object* sender,
  8. Func1 signal,
  9. typename QtPrivate::FunctionPointer<Func2>::Object* receiver,
  10. Func2 slot)
  11. {
  12. QMetaObject::Connection conn_normal = QObject::connect(sender, signal, receiver, slot);
  13. QMetaObject::Connection* conn_delete = new QMetaObject::Connection();
  14. *conn_delete = QObject::connect(sender, signal, [conn_normal, conn_delete]() {
  15. QObject::disconnect(conn_normal);
  16. QObject::disconnect(*conn_delete);
  17. delete conn_delete;
  18. });
  19. return conn_normal;
  20. }
  21. template <typename Func1, typename Func2, typename std::enable_if_t<!std::is_member_pointer<Func2>::value, int> = 0>
  22. static inline QMetaObject::Connection weakConnect(typename QtPrivate::FunctionPointer<Func1>::Object* sender,
  23. Func1 signal,
  24. Func2 slot)
  25. {
  26. QMetaObject::Connection conn_normal = QObject::connect(sender, signal, slot);
  27. QMetaObject::Connection* conn_delete = new QMetaObject::Connection();
  28. *conn_delete = QObject::connect(sender, signal, [conn_normal, conn_delete]() {
  29. QObject::disconnect(conn_normal);
  30. QObject::disconnect(*conn_delete);
  31. delete conn_delete;
  32. });
  33. return conn_normal;
  34. }
  35. template <typename Func1, typename Func2, typename std::enable_if_t<!std::is_member_pointer<Func2>::value, int> = 0>
  36. static inline QMetaObject::Connection weakConnect(typename QtPrivate::FunctionPointer<Func1>::Object* sender,
  37. Func1 signal,
  38. typename QtPrivate::FunctionPointer<Func2>::Object* receiver,
  39. Func2 slot)
  40. {
  41. Q_UNUSED(receiver);
  42. QMetaObject::Connection conn_normal = QObject::connect(sender, signal, slot);
  43. QMetaObject::Connection* conn_delete = new QMetaObject::Connection();
  44. *conn_delete = QObject::connect(sender, signal, [conn_normal, conn_delete]() {
  45. QObject::disconnect(conn_normal);
  46. QObject::disconnect(*conn_delete);
  47. delete conn_delete;
  48. });
  49. return conn_normal;
  50. }
  51. #endif // WEAKCONNECT_H