How to resolve the ambiguity of the function in qt slot

Viewed 600

I want to connect a function to a slot and this is my code.

I get error that no instance of overloaded function matched the argument list.

connect(lineEditCommandInterface, &QLineEdit::textChanged, this, &SUMMIT::ReceiveCommand);

the issue is that ReceiveCommand is a overloaded function and i want to use the function with no arguments.

  void ReceiveCommand();
  void ReceiveCommand( std::string stdstrCommand);
3 Answers

One possible solution is to use a lambda function:

connect(lineEditCommandInterface, &QLineEdit::textChanged, [this](){
   ReceiveCommand(); 
});

Aanother option could be static casting the slot, just in case you may skip the lambda....

slots:
void fooSlot(int x);
void fooSlot(const QString& n);

then

connect(someObject, &SomeClass::someSignal, this, static_cast<void(MainWindow::*)(const QString&)>(&MainWindow::fooSlot));
connect(someObject, &SomeClass::someSignal, this, static_cast<void(MainWindow::*)(int)>(&MainWindow::fooSlot));

Since Qt 5.6, the recommended (or at least less verbose) way to connect to overloaded signals/slots is with QOverload::of() (which isn't well documented). With Qt 5.7+ and C++14 one can also use qOverload() and friends. Though this doesn't help with mismatched signal/slot parameters, it seems worth pointing out.

Example with C++11 and QOverload:

connect(object, &SomeClass::someSignal, this, QOverload<void>::of(&SUMMIT::ReceiveCommand));

The various options are documented with examples (including the old static_cast method) in: Selecting Overloaded Signals and Slots

Also of possible interest in regards to this question is the section in the same doc: Using Default Parameters in Slots to Connect to Signals with Fewer Parameters. The lambda option is also documented higher up on that page.

Further examples of using QOverload can be found in Qt docs for just about every overloaded signal, (eg. SpinBox::valueChanged()) but it also works for slots.

Related