How to set Font for widgets in the parent from a child widget
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.
Code:
void UpdateFont()
{
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.
Re: How to set Font for widgets in the parent from a child widget
Not tested, but shouldn't do QApplication::setFont() the trick?
EDIT: No, only changes the default font... sorry.
EDIT EDIT: Umpf... Yes it works!
Re: How to set Font for widgets in the parent from a child widget
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);
Re: How to set Font for widgets in the parent from a child widget
Thanks Lykurg and SantoshReddy.
Re: How to set Font for widgets in the parent from a child widget
Your segmentation faults come from assuming pointers are valid and point to things of certain types:
Code:
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.