[Qt-interest] Sanity check on using dynamic_cast<> with Qt

Andre Somers andre at familiesomers.nl
Tue May 11 08:56:52 CEST 2010


On 11-5-2010 0:32, K. Frank wrote:
> Hello List -
>
> I get a QWidget* out of a QTableWidget cell and I need to cast it to
> derived type.
>
> Using C++'s dynamic_cast<>  seems to do the trick, but I would like to check
> that this is the Qt-approved way of doing things.  (I seem to recall that Qt has
> its own casting support, but that it is restricted to QVariant.)  Is
> this the right
> approach?
>
> More specifically,
>
>     QTableWidget::cellWidget (row, column)
>
> returns a QWidget*, previously set with
>
>     QTableWidget::setCellWidget (row, column, new RadioBox())
>
> where RadioBox is my class that derives from QGroupBox (which, itself, derives
> from QWidget).
>
> I need to access the value() member function of my RadioBox class, and I do so
> as follows:
>
>     int value = dynamic_cast<RadioBox*>(tableWidget->cellWidget (row,
> column))->value();
>
> Is this the preferred Qt way of doing this?
>    
No, it is a recipe for segfaults. If you do a cast, first check the 
return value to see if you did not end up with a 0 pointer. In your 
code, you are potentially dereferencing a 0 pointer by directly invoking 
the value() method on it. If the cast returns 0, it will crash. So:

RadioBox* rb = dynamic_cast<RadioBox*>(tableWidget->cellWidget (row, 
column));
if (!rb) {
     //not good! Do something to recover from this error
     return;
}
int value = rb->value();

Qt offers qobject_cast, which is usefull especially across library 
boundaries.

André




More information about the Qt-interest-old mailing list