[Qt-interest] Calling parent Widget slot

Justin Noel justin at ics.com
Thu Apr 9 17:14:11 CEST 2009


Donal O'Connor wrote:
> Hi There,
>
> I have a custom widget and in it's constructor I pass a parent
> widget's pointer. The parent is also a custom widget (QWidget) with a
> custom slot.
>
> For exampe:
>
> MyCustomWidget(QWidget * parent )
>    : QWidget(parent)
> {
> }
>
> In the custom child widget, I now want to call the parent's custom
> slot from the child. I am doing it this way:
>
> (static_cast<ParentWidgetType*>(parentWidget()))->setStatus(tr("Update
> Status"));
>
>
> The reason for the cast is I need to access the custom slot I've
> implemented.
>

If this widget needs a special parent why not enforce that in the
constructor arguments and keep a QPointer<> wrapped member variable of
the correct type to access it. It's going to be much much safer than
static_cast. Depending on the usage here, you could have a signal/slot
interface to set status, connect it in the ctor and skip the
member/function calling entirely.

> Now this works fine, until I try and change a member variable in the
> setStatus(const QString & statusText) method.
> For example:
>
> void ParentWidgetType::setStatus(const QString & statusText)
> {
>     m_status->setText(statusText);
> }
>
> This creates a *segmentation fault*, where as
>
> void ParentWidgetType::setStatus(const QString & statusText)
> {
>      qDebug() << "Hello";
> }
>
> It isn't a case that the m_status isn't created already, it is
> initialized in the constructor as:
>
> m_status = new QLabel("No Status");
>
> I also called the slot within the Parent widget and I've no problems.
>
> Forgive me if this is more a C++ problem rather than QT.
>
> Am I missing something obvious?
>

It's probably a C++ issue. Make a minimum example and post it if it's
still an issue. I have a feeling you may have done something like this:

ParentWidgetType::ParentWidgetType()
{
    //Wrong! This makes a local variable that shadows the member variable
    QLabel* m_status = new QLabel("NoStatus");

   //Right! Initializes a member
   m_status = new QLabel("NoStatus");
}


-------------- next part --------------
A non-text attachment was scrubbed...
Name: justin.vcf
Type: text/x-vcard
Size: 233 bytes
Desc: not available
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090409/ea7eae74/attachment.vcf 


More information about the Qt-interest-old mailing list