I have problems with a simple application in Qt. The app looks like a simple calculator wtih buttons (digits from 0 to 9).
Once a button is clicked application shall display on the application’s output the corresponding number as a digit and as a numeral (a word).
I need to use QSignalMapper. How can I solve this?
My code so far:
QLayout* Widget::createButtons()
{
QGridLayout *lt = new QGridLayout(this);
QSignalMapper *signalMapper = new QSignalMapper(this);
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(keyPressed(int)));
QString txtButtons[10] = {"zero", "one", "two",
"three", "four", "five",
"six", "seven", "eight",
"nine"};
for(int i=0; i<10; i++) {
buttons[i] = new QPushButton(txtButtons[i], this);
signalMapper->setMapping(buttons[i], i);
connect(buttons[i], SIGNAL(clicked()), signalMapper, SLOT(map()));
lt->addWidget(buttons[i], i/3, i%3);
}
return lt;
}
void Widget::keyPressed(int buttonID)
{
qDebug() << QString::number(buttonID) + " was clicked";
}
See this question for three ways of mapping one of a multitude of objects to a value. The use of
QSignalMapperis not necessary in Qt 5, and is optional in Qt 4.Below is an example of the use of
QSignalMapperin Qt4/5. There are three points to keep in mind to useQSignalMapper:Use the
setMappingmethod to add a mapping between a senderQObjectinstance, and a value (integer, string, etc.).Connect the sender's signal to the
mapslot in the mapper.Connect the mapper's
mapped(ValueType)signal to the consumer of the mapping.ValueTypeis the type you're mapping to - here, it'd beQString.