T qobject_cast(QObject *object)
A functionality which is added by deriving from QObject
and using the Q_OBJECT
macro is the ability to use the qobject_cast
.
Example:
class myObject : public QObject
{
Q_OBJECT
//...
};
QObject* obj = new myObject();
To check whether obj
is a myObject
-type and to cast it to such in C++ you can generally use a dynamic_cast
. This is dependent on having RTTI enabled during compilation.
The Q_OBJECT macro on the other hands generates the conversion-checks and code which can be used in the qobject_cast.
myObject* my = qobject_cast<myObject*>(obj);
if(!myObject)
{
//wrong type
}
This is not reliant of RTTI. And also allows you to cast across dynamic library boundaries (via Qt interfaces/plugins).