What is different between dynamic_cast and qobject_cast
What is different between dynamic_cast
and qobject_cast
?
-
qobject_cast
can only be used withQObject
derived classes havingQ_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://blog.csdn.net/Stephen___Qin