c++ - Connecting overloaded signals and slots in Qt 5 -


i'm having trouble getting grips new signal/slot syntax (using pointer member function) in qt 5, described in new signal slot syntax. tried changing this:

qobject::connect(spinbox, signal(valuechanged(int)),                  slider, slot(setvalue(int)); 

to this:

qobject::connect(spinbox, &qspinbox::valuechanged,                  slider, &qslider::setvalue); 

but error when try compile it:

error: no matching function call qobject::connect(qspinbox*&, <unresolved overloaded function type>, qslider*&, void (qabstractslider::*)(int))

i've tried clang , gcc on linux, both -std=c++11.

what doing wrong, , how can fix it?

the problem here there two signals name: qspinbox::valuechanged(int) , qspinbox::valuechanged(qstring). need tell qt 1 want pick, casting right type:

connect(spinbox, static_cast<void (qspinbox::*)(int)>(&qspinbox::valuechanged),         slider, &qslider::setvalue); 

i know, it's ugly. there's no way around this. today's lesson is: do not overload signals , slots!


addendum: what's annoying cast

  1. one repeats class name twice
  2. one has specify return value if it's void (for signals).

so i've found myself seldomly using c++11 snippet:

template<typename... args> struct select {      template<typename c, typename r>      static constexpr auto overload_of( r (c::*pmf)(args...) ) -> decltype(pmf) {          return pmf;     }  }; 

usage:

connect(spinbox, select<int>::overload_of(&qspinbox::valuechanged), ...) 

i find not useful. expect problem go away when creator (or ide) automatically insert right cast when autocompleting operation of taking pmf. in meanwhile...

note: pmf-based connect syntax does not require c++11!


addendum 2: in qt 5.7 helper functions added mitigate this, modelled after workaround above. main helper qoverload (you've got qconstoverload , qnonconstoverload).

usage example (from docs):

struct foo {     void overloadedfunction();     void overloadedfunction(int, qstring); };  // requires c++14 qoverload<>(&foo:overloadedfunction) qoverload<int, qstring>(&foo:overloadedfunction)  // same, c++11 qoverload<>::of(&foo:overloadedfunction) qoverload<int, qstring>::of(&foo:overloadedfunction) 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -