user7751065
user7751065

Reputation:

Signal and slot for multiple widgets

I have three pushbutton widgets in my class and i want to connect the clicked signals from all of the three to one slot. Here is what my syntax looks like:

QObject::connect(PtrLineedit1, SIGNAL(Clicked()), this, SLOT(myslot()));
QObject::connect(PtrLineedit2, SIGNAL(Clicked()), this, SLOT(myslot()));
QObject::connect(PtrLineedit3, SIGNAL(Clicked()), this, SLOT(myslot()));

But the above syntax is not working. And the above syntax i am using in one of my WizardPage class. this Wizard has three pages, and in one of the page(class) has three pushbuttons and in this class constructor i am trying to achieve. I have used "clicked()" too, but no luck

Upvotes: 1

Views: 561

Answers (1)

Mikhail Churbanov
Mikhail Churbanov

Reputation: 4500

First of all, there is no signal "Clicked", but there is "clicked" - the lowercase one.

Second - it's better not to use the macros SIGNAL and SLOT - they are error prone, like in your case. If you look inside them, they are generating a string, which could not be checked by compiler. Instead better to use following syntax:

QObject::connect(PtrLineedit1, &LineEditClass::clicked, this, &ThisClass::myslot);

Cause if you will write then:

QObject::connect(PtrLineedit1, &LineEditClass::Clicked, this, &ThisClass::myslot);

It would produce the error during compilation, in case when LineEditClass::Clicked is not defined. This would protect you from typos.

UPD: As eventually I've found another your question which faces issue relevant to this one, I've updated this answer with more details, which might be helpful for others.

In case of overloaded methods, you must explicitly tell compiler which one should be used - for example we have following:

void QComboBox::currentIndexChanged(int index)
void QComboBox::currentIndexChanged(const QString &text)

thus the &QComboBox::currentIndexChanged could be resolved ambigously, and you will get the compilation error. To fix it you need to explicitly tell what are the arguments of the function you want to connect to:

QObject::connect(comboBox, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ThisClass::myComboBoxSlotWithIntArg);

or

QObject::connect(comboBox, static_cast<void(QComboBox::*)(const QString &)>(&QComboBox::currentIndexChanged), this, &ThisClass::myComboBoxSlotWithStringArg);

Upvotes: 6

Related Questions