PDA

View Full Version : casting complex widget pointers



TheKedge
7th February 2007, 19:40
Hello,

I've got a class facading two classes, each with its own UI. I don't know at compile time which of these UIs will be shown.

How can I make a function that returns a pointer to on of the UIs:


QWidget* facade::widget()
{
if (suchAndSuc)
return new class1UI;
else
return class2UI;
}


or is this the wrong approach?

I'm trying to keep everything as modular as possible - each class should bring its own UI with it - but I don't know which classes will be used. So how do I build a form with widgets without knowing their type?
Could just make sure that all the UIs have a common type as parent and pass this as a pointer? i.e. CommonUI* widget(){return new class1UI;}

thanks
K

wysota
7th February 2007, 20:06
If you'll just be passing QWidget pointers, you should be safe (that's what Designer does). Then you can use qobject_cast to cast the result to more complex types if you need them.

TheKedge
7th February 2007, 20:34
well, I've got something like:


class UI_one : public QWidget
{
private:
QLabel* l;
QTextEdit* txt;
QPushButton* btn;
//some signals and slots
}

class UI_two : public QWidget
{
QPushButton* btn1;
QPushButton* btn2;
//...
}

//facade implementation
QWidget* facadeUI::showUI
{
if(condition)
//need to pass pointer to class UI_one
return (QWidget*)new UI_one;//is cast like this ok?
else
//need to pass pointer to class UI_two
return (QWidget*)new UI_one;//???
}

//building the user interface
CompleteUI::show()
{
QWidget* someWidget = facade->showUI()
someWidget ->show();//shows on its own
//or
someLayout->addWidget(someWidget );//how it as part of something else
}


is that what you mean? - can I down-cast for the pass and still use them properly?
thanks
K

TheKedge
8th February 2007, 13:47
ok, I've done it, and it works fine.
I didn't find it obvious that casting a a pointer to something derived from a widget to a widget pointer would work.

thanks for the help,
K

Chicken Blood Machine
8th February 2007, 19:52
You don't need those casts either.



QWidget* facadeUI::showUI
{
if(condition)
//need to pass pointer to class UI_one
return new UI_one;
else
//need to pass pointer to class UI_two
return new UI_two;

}


Also make sure you have a guard so that you don't create new objects everytime showUI is called (unless that is what you intended).