[Qt-interest] Calling parent Widget slot
Donal O'Connor
donaloconnor at gmail.com
Thu Apr 9 18:25:57 CEST 2009
Thanks very much for the explanation!
On Thu, Apr 9, 2009 at 4:58 PM, Ian Thomson <Ian.Thomson at iongeo.com> wrote:
> Hi,
>
> Donal O'Connor wrote:
> > Now this works fine, until I try and change a member variable in the
> > setStatus(const QString & statusText) method.
>
> In case you are wondering why this happens, it's because static_cast
> only does compile-time type checking. If you give it a QWidget pointer
> and static cast it to ParentWidgetType pointer, it will only check that
> such a cast can possibly make sense. Of course it is possible because
> ParentWidgetType derives QWidget, so the static cast will succeed
> regardless of whether you really give it a ParentWidgetType or any other
> QWidget type.
>
> If you do such a cast on a QWidget which isn't a ParentWidgetType and
> call a functions on it, they may or may not succeed. If a function
> doesn't actually do anything specific to ParentWidgetType, then it might
> well succeed, but if it starts look at member functions then it's likely
> to crash horribly. I suspect that this is what you did. Your
> parentWidget() was probably a different widget from what you expected.
>
> The safe way to do such a cast it like this:
> ParentWidgetType* parent = dynamic_cast<ParentWidgetType*>(parentWidget());
> if (parent)
> parent->setStatus(tr("Update Status"));
>
> dynamic_cast does a runtime type check which will return a null pointer
> if the cast is not possible. However dynamic_cast is quite slow and Qt
> provides an alternative for QObject types called qobject_cast which is
> used in the same way as dynamic_cast, but has added benefits. See:
> http://doc.trolltech.com/4.5/qobject.html#qobject_cast
>
> However the signal/slot way is the best approach because it keeps
> objects self-contained.
>
> Cheers,
> Ian.
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090409/2df1f036/attachment.html
More information about the Qt-interest-old
mailing list