12.2.  Type Identification and qobject_cast

[ fromfile: qtrtti.xml id: qtrtti ]

  1. qobject_cast

  2. QObject::inherits()

  DestType* qobject_cast<DestType*> ( QObject * qoptr )
[Note]Note
  • The implementation of qobject_cast makes no use of C++ RTTI.

  • The code for this operator is generated by the MetaObject Compiler (moc).

[Note] Multiple Inheritance and qobject_cast

For qobject_cast to work for the non-QObject base classes, you need to place each base class in a Q_INTERFACES(BaseClass1 BaseClass2) line, in the class definition after the Q_OBJECT macro.

Example 12.2. src/qtrtti/qtrtti.cpp

[ . . . . ]

//  QWidget* w = &s;            1
    
    if (w->inherits("QAbstractSlider"))  cout << "Yes, it is ";
    else cout << "No, it is not";
    cout << "a QAbstractSlider" << endl;
    
    if (w->inherits("QListView")) cout << "Yes, it is ";
    else  cout << "No, it is not ";
    cout << "a QListView" << endl; 

    return 0;
}

1

A pointer to some widget