PDA

View Full Version : qobject_cast for Qt3 ?



sunil.thaha
15th December 2006, 13:50
Hi Guys,

Just thought like making a qobject_cast for Qt3.
This template functon in Qt4 helps us avoid a lots of typo's So I just thought like making one. this is an intial draft, so please give your suggestions

So here goes the qobject_cast


template < typename T >
inline T* qobject_cast( QObject *object ){
QObject tmp;
T instance( &tmp);
if( object->inherits( instance.className()) ){
return dynamic_cast< T* >( object );
}
return 0;
}
Simple Test App


#include <qpushbutton.h>
#include <qapplication.h>

template < typename T >
inline T* qobject_cast( QObject *object ){
QObject tmp;
T instance( &tmp);
if( object->inherits( instance.className()) ){
return dynamic_cast< T* >( object );
}
return 0;
}

int main( int argc, char *argv[] ){

QApplication app( argc, argv );
QObject *obj = new QPushButton(0, "Name");

QPushButton *b = qobject_cast<QPushButton>( obj );
if( b ){
qDebug( b->name() );
}
return 0;
}

My inital intend was to create a qobject_cast was
QPushButton *b = qobject_cast< QPushButton * >( object );
Note that the * is missing in the version I have written. Any Ideas ?

Glitch
15th December 2006, 16:47
qobject_cast was added to work around problems with dynamic cast over shard objects and the lack of dynamic_cast when RTTI is turned off. I think your code might still exhibit these issues. If you pass the moc inherits test I think you are safe with a static_cast<> which wil work.

--Justin

camel
16th December 2006, 12:54
Hi Guys,

Just thought like making a qobject_cast for Qt3.


What is the difference between qtobject_cast in Qt4 and qt_cast in Qt3?

qt_cast is defined in objectdefs.h

sunil.thaha
18th December 2006, 05:12
Hey that clue was good I looked in the qobjectdefs.h & then I stumbled upon staticMetaObject() atleast it is there in Qt 3.3.6

So I re wrote the qobject_cast And Guess what ?? you can use qobject_cast< QClassName *>( object );

And for qt_cast : I have no clue :confused: ( atleast for now )

So here is the new Code qobject_cast


#include <qmetaobject.h>

template < typename T >
inline T qobject_cast( QObject *object ){
T dummy;
if( object->inherits( dummy->staticMetaObject()->className()) ){
return static_cast< T >( object );
}
return 0;
}


And the Driver still remains the same for most of its part except that now we can use the cast similar to Qt4 's



#include <qmetaobject.h> // staticMEtaObject used

#include <qpushbutton.h>
#include <qcombobox.h>
#include <qapplication.h>


template < typename T >
inline T qobject_cast( QObject *object ){
T dummy;
if( object->inherits( dummy->staticMetaObject()->className()) ){
return static_cast< T >( object );
}
return 0;
}

int main( int argc, char *argv[] ){

QApplication app( argc, argv );
QObject *obj = new QPushButton(0, "Name");

QComboBox *b = qobject_cast<QComboBox*>( obj );
if( b ){
qDebug( b->name() );
}else {
qDebug( "Could not typcast ");
}
return 0;
}