[Qt-interest] Calling parent Widget slot
Ian Thomson
Ian.Thomson at iongeo.com
Thu Apr 9 17:58:15 CEST 2009
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.
More information about the Qt-interest-old
mailing list