get my widget from QStackedWidget
Hi,
I have a QSteckedWidget on my gui and I put my own widgets on it, showing the actual one depending on some choices made on the other parts of the gui. I can set this with QStackedWidget::setCurrentIndex().
Now I need the reverse: I would like to use some functions that belong to the current widget. here is some pseudo-code:
Code:
//I have a class like this:
{
//...
public:
void myfunction(); // this is what I want to reach
}
//this is in the mainWindow class somewhere:
//I made the stackedwidget in the code, say with the name myStackedWidget
myStackedWidget->setCurrentIndex(i); //shows the wanted widget correctly
//and here I need to access the current widget that is shown
myStackedWidhet->currentWidget(i)->myfunction();//does not work
the error message says:
"class QWidget has no member named 'myfunction()'"
This shows that what I can get with this function is a Widget, but not the myC. How can I solve this?
Re: get my widget from QStackedWidget
try :
Code:
myC *myWidget = static_cast<myC *>(myStackedWidhet->currentWidget(i));
if ( myWidget )
myWidget->myfunction();
Re: get my widget from QStackedWidget
static_cast will always succeed, so the if condition will always be true. Use dynamic_cast
Re: get my widget from QStackedWidget
Thans, it works now. (of course I don't need i int the function currentWidget, but that is of course just a mistype)
But there are some "but"-s.
1st - static_cast works also
2nd - why should I use dynamic_cast instead?
3rd - what do I do exactly? How does a type cast like this works, why do I need it? I mean this does not look pretty enough compared to the feeling that this should not be a very new problem and I've just simply got used to that in the programming world if a problem should have been a problem for at least 1000 people before me than there is a pretty straightforward solution. This look a little bit strange to me that's all.
Re: get my widget from QStackedWidget
static_cast will always return a non-zero pointer if given a non-zero pointer: regardless of safety. Your if() is testing the pointer for null as a safety check but this won't fail (nish's point above).
dynamic_cast will only return non-zero pointer if the given pointer can be safely treated as a pointer to the type you are casting to.
You need a cast because the QStackedWidget maintains a list of pointers to QWidget and currentWidget() returns these, not a pointer to your type. A pointer to your type is required in order to access methods unique to your type.