[Interest] type casting 5 levels down no error but not proper

Rainer Wiesenfarth Rainer_Wiesenfarth at trimble.com
Tue Apr 24 14:18:49 CEST 2012


Am 24.04.2012 13:58, schrieb Sujan Dasmahapatra:
> I have my mainwindow which is QMainWindow the parent of all my other
> classes. I am type casting upwards from 5 levels down using
> reinterpret_cast, to access the mainwindow to display message using
> statusBar(), but when type casting it's not giving error but when
> accessing mainwindow->statusBar() it's crashing.
>
> please check the code snippet below:
>
> [code]
> QWidget *wid = reinterpret_cast<QWidget *>(parent());
> CSheet *sheet = reinterpret_cast<CSheet *>(wid->parent());
> QScrollBar *scrollBar = reinterpret_cast<QScrollBar *>(sheet->parent());
> CTabWidget *tabWid = reinterpret_cast<CTabWidget *>(scrollBar->parent());
> CDataPage *dataPage = reinterpret_cast<CDataPage *>(tabWid->parent());
> MainWindow *mainwin = reinterpret_cast<MainWindow *>(dataPage->parent());
> mainwin->statusBar()->showMessage(tr("A new plot being added!!"),5000);
> //Here it is crashing
> [/code]

1. (as others mentioned) use dynamic_cast<>() and check the return value
2. take a look at QWidget::window (), probably this works:
   MainWindow *mainwin = dynamic_cast<MainWindow*>(window());
   if (mainwin)
   {
     mainwin->statusBar()->showMessage(...);
   }
3. re-think your design and maybe even your architecture, as a (very) 
low level widget in the hierarchy should not make assumptions like this 
about its parents. How would your piece of code be ever reusable?

Best Regards / Mit freundlichen Grüßen
Rainer Wiesenfarth

-- 
Tel.: +49 (0)711 22 88-10  *  Fax: +49 (0)711 22 88-111
Web: http://www.trimble.com/geospatial/  *  http://www.inpho.de/
Trimble Germany GmbH  *  Branch office Stuttgart
Rotebühlstraße 81  *  70178 Stuttgart  *  Germany
Commercial register: HRB 83893, Darmstadt
Managing Directors: Dr. Frank Heimberg, Hans-Jürgen Gebauer

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 4489 bytes
Desc: S/MIME Kryptografische Unterschrift
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20120424/9c1a7b20/attachment.bin>


More information about the Interest mailing list