PDA

View Full Version : How to set Font for widgets in the parent from a child widget



ramsailesh
7th January 2013, 13:23
Dear all,

I've a mainwindow M with some widgets L and a Custom-dropdown D which contains list of Fonts.
I need to set font for all the widgets in M if dropdown D is changed.
I tried to set the font which resulted in Segmentation fault.



void UpdateFont()
{
QObject *obj = this->parent();
QObjectList objlistChildren = obj->children();
int iCount = objlistChildren.count();

for(int iIndex = 0; iIndex < iCount; iIndex++)
{
QObject *temp = objlistChildren[iIndex];
( (QWidget*)objlistChildren[iIndex] )->setFont(font);
}
}


How can i access the parent widgets and set its font from the child control.

Thanks in advance for your suggestions.

Lykurg
7th January 2013, 13:30
Not tested, but shouldn't do QApplication::setFont() the trick?

EDIT: No, only changes the default font... sorry.

EDIT EDIT: Umpf... Yes it works!

Santosh Reddy
7th January 2013, 14:09
1. Emit a signal from the child widget (L) to indicate that font has changed, eg. emit fontChanged(font);
2. Connect this signal to the Mainwindow's (M) slot where you set the font, eg. M->setFont(font);

ramsailesh
7th January 2013, 17:39
Thanks Lykurg and SantoshReddy.

ChrisW67
7th January 2013, 23:43
Your segmentation faults come from assuming pointers are valid and point to things of certain types:


void Class::UpdateFont()
{
QObject *obj = this->parent(); // this can be NULL
QObjectList objlistChildren = obj->children(); // which will crash here
int iCount = objlistChildren.count();

for(int iIndex = 0; iIndex < iCount; iIndex++)
{
QObject *temp = objlistChildren[iIndex];
( (QWidget*)objlistChildren[iIndex] )->setFont(font); // what do you suppose happens if the child is not a QWidget?
}
}

You should get out of the habit of using C-style casts preferring C++-style casts of the correct type. Casts in general are last-resort mechanisms and worthy of avoidance. In this circumstance you could use qobject_cast and check the cast was successful.