Aquarius TheGirl Aquarius TheGirl - 8 days ago 6
C++ Question

Why is qobject_cast required in this SLOT for sender()?

From calculator example of Qt:

void Calculator::digitClicked()
{
Button *clickedButton = qobject_cast<Button *>(sender());
int digitValue = clickedButton->text().toInt();
if (display->text() == "0" && digitValue == 0.0)
return;

if (waitingForOperand) {
display->clear();
waitingForOperand = false;
}
display->setText(display->text() + QString::number(digitValue));
}


This SLOT is connected to all digit buttons:

digitButtons[i] = createButton (QString::number(i), SLOT(digitClicked()));


With
createButton
:

Button *Calculator::createButton(const QString &text, const char *member)
{
Button *button = new Button(text);
connect(button, SIGNAL(clicked()), this, member);
return button;
}


So, in the SLOT why is type cast required?

Button *clickedButton = qobject_cast<Button *>(sender());

Answer

Basically, sender() returns a QObject*, so you will not be able to call methods of the underlying object until it is downcasted.

qobject_cast performs the downcast, while checking at runtime the underlying object is effectively of the required type. This is similar to standard dynamic_cast, except it has a reduced cost due to Qt's meta-object facilities (but it only works with classes derived from QObject).

See Qt's documentation about meta-object system.