How to check if the parent widget of a certain type?
-
Hi
Say I have MyWidgetContainer that is subclassed of QWidgetclass MyWidgetContainer: public QWidget { ..... }
and I have CustomWidget, this widget will do special behaviour if it is only a child of MyWidgetContainer.
void CustomWidget::doSpecialBehaviour() { //if parent widget == MyWidgetContainer // do the special behaviour //else //do the normal behaviour }
How can I achieve something like this?
-
Hi
Say I have MyWidgetContainer that is subclassed of QWidgetclass MyWidgetContainer: public QWidget { ..... }
and I have CustomWidget, this widget will do special behaviour if it is only a child of MyWidgetContainer.
void CustomWidget::doSpecialBehaviour() { //if parent widget == MyWidgetContainer // do the special behaviour //else //do the normal behaviour }
How can I achieve something like this?
@abdoemr11 Use
if(MyWidgetContainer *w = qobject_cast<MyWidgetContainer *>(parentWidget())){ // FIXME }
-
Hi
Say I have MyWidgetContainer that is subclassed of QWidgetclass MyWidgetContainer: public QWidget { ..... }
and I have CustomWidget, this widget will do special behaviour if it is only a child of MyWidgetContainer.
void CustomWidget::doSpecialBehaviour() { //if parent widget == MyWidgetContainer // do the special behaviour //else //do the normal behaviour }
How can I achieve something like this?
@abdoemr11
You can do this with casting, but you are not supposed to. It is not considered good practice to write child code to depend on what its parent is, why do you want to design like this? -
@abdoemr11
You can do this with casting, but you are not supposed to. It is not considered good practice to write child code to depend on what its parent is, why do you want to design like this? -
@JonB create a virtual function specialBehaviour in parent class and override it in all children classes.
do something inside specialBehaviour() of custom widget
leave it empty in other widget classes. -
if(parentWidget->metaObject()->className() == "MyWidgetContainer") { // FIXME }
But the solution proposed by @eyllanesc is much better - less error prone and compiler will be able to check it more.
-
if(parentWidget->metaObject()->className() == "MyWidgetContainer") { // FIXME }
But the solution proposed by @eyllanesc is much better - less error prone and compiler will be able to check it more.
But the solution proposed by @eyllanesc is much better - less error prone and compiler will be able to check it more.
As some other replies have mentioned, the casting although technically feasible (you have some code snippets already) might not be a good design approach.
Let's say in a month you want the same custom behavior when the container widget is MyUncleContainer, not only MyParentContainer...