Question

I'm trying to cast a QTableWidgetItem into a child class. I have a class hierarchy like this:

(Parent -> Child)
QTableWidgetItem -> SortableTableWidgetItem -> EnhancedTableWidgetItem

or

class SortableTableWidgetItem : public QTableWidgetItem

class EnhancedTableWidgetItem : public SortableTableWidgetItem

For the most part, I use the items as QTableWidgetItems because that code is already written and shouldn't change. However in some instances I need to access data in the EnhancedTableWidgetItem after being given a pointer to QTableWidgetItem (which I know is an EnhancedTableWidgetItem because I constructed the object and passed it to the calling code initially). I have tried casting like this:

QTableWidgetItem item = getItem();

// This fails to compile saying "error: no matching function for call to ‘qobject_cast(QTableWidgetItem*)’"
EnhancedTableWidgetItem *eItem = qobject_cast<EnhancedTableWidgetItem*>( item );

// This also fails to compile and says: "error: invalid conversion from ‘QTableWidgetItem*’ to ‘EnhancedTableWidgetItem*’"
EnhancedTableWidgetItem *eItem = dynamic_cast<EnhancedTableWidgetItem*>( item );

I come from the Java world where this is perfectly legal and is done all the time. Why can't I cast the base class pointer into a child class pointer? How can I accomplish this?

Was it helpful?

Solution

qobject_cast is only for a class which inherit from QObject. If item is really of your custom type then use dynamic cast

EnhancedTableWidgetItem* eItem = dynamic_cast<EnhancedTableWidgetItem*>( item );

Nevermind. you are casting an object to a pointer. It will not work. Still, what I previously said still apply

OTHER TIPS

You're getting mixed up with pointers and values. I think your getItem() should not return value (copy), it should return a pointer, so have this:

QTableWidgetItem *item = getItem(); // getItem() returns pointer
auto eItem = dynamic_cast<EnhancedTableWidgetItem*>( item );

(Using auto of C++11 above, which is much nicer, but if you're stuck with older compiler, then use EnhancedTableWidgetItem* instead.)

QTableWidgetItem is not derived from QObject, thus it cannot use qobject_cast<>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top