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!" );
}
posted @ 2020-07-14 00:20  心媛意码  阅读(199)  评论(0编辑  收藏  举报