Casting Parent Object Not Working QT 5.2.1
Hello, I am trying to cast the parent widget in the child widget.
this is how I create the ControlBar object inside a member function of class MainTabs
ControlBar * cb = new ControlBar(this);
I then cast the parentWidget to type MainTabs
MainTabs* mt = qobject_cast<MainTabs*>(parentWidget());
if (mt ==0)
qDebug() << "error with the cast";
The cast fails.
not sure why?
[edit: added missing coding tags @ SGaist]
@ControlBar * cb = new ControlBar(this);@
I suppose that MainTabs is the "this" here, right ?
now there's a change of parent thus your cast will fail.
Anyway, it's always a Bad Idea (™) to start casting the parent widget inside a child widget. If the child widget needs to know its parent for some reason then there's generally a design flow somewhere. e.g. You need the value of a property of the parent to set something in your child widget then you should rather give that child a setter or a constructor with a parameter that the parent will call with the right value.
Think of this: you want to change your parent widget for something else, right now you also have to alter the code of your child widget.
Hope it helps
What I am trying to do is change the text of the tabs from within the ControlBar class.
I can not think of a way to get a reference to the QTabWidget from ControlBar. I guess I could pass the QTabWidget to the constructor.
I need to know the index of the tab in order to change its text, so I planned to use QTabWidget.indexOf( ControlBar*); and then I have the index.
is the preferred way to pass an instance of the parent to the child?
I got it to work by passing ui->mainTabControl to the constructor of my ControlBar class.
I guess passing an instance of what you need to the constructor is the preferred way?
this is what is in my MainTabs class
ControlBar * cb = new ControlBar(this,ui->mainTabControl);
This is what is in my ControlBar class
int currentIndex = _mainTabControl->indexOf(this);
Do you plan to change the title several times ?