What is different between dynamic_cast and qobject_cast

What is different between dynamic_cast and qobject_cast?

  • qobject_cast can only be used with QObject derived classes having Q_OBJECT macro.

  • qobject_cast doesn't use RTTI.

A resent usage of qobject_cast is getting a pointer to a class inside a slot:

QObject::connect( btn, &QPushButton::clicked, this, &MyClass::onClicked );
void MyClass::onClicked()
{
    // How to get pointer to a button:
    QObject *p = sender();
    // It's QObject. Now we need to cast it to button:
    QPushButton *btn = qobject_cast<QPushButon *>( p );
    Q_ASSERT( btn != nullptr ); // Check that a cast was successfull
    // Now we can use a QObject as a button:
    btn->setText( "We just clicked on a button!" );
}
原文地址:https://www.cnblogs.com/Stephen-Qin/p/13296784.html