[Qt-interest] Generic input widgets for varying types - how to?

Helge Preuss helge.preuss at gmx.net
Fri Mar 27 21:21:00 CET 2009


Nathan Carter wrote:
> How about changing the relationship from is-a to has-a?  Just make  
> your ParameterInput inherit from QHBox instead, and put the  
> appropriate input widget inside, based on the type?
>   
Right, I just had this idea too. I was thinking "QWidget" though. Would
using a QHBox take care of resizing, moving, etc. the inner widget
automatically? Then that would be the better choice, of course.
> You should also consider just making one class, not many, and using an  
> enum for types, and returning QVariants.  (They already have the type  
> enum built-in.)  
I'm not familiar with the QVariant class, but from scanning the
documentation I gather that it is a union for /Qt/ classes. I need to
define my own widgets. That would rule out this idea, right?

Thanks,

Helge
> Something like this:
>
> class ParameterInput : public QHBox
> {
> private:
> 	QVariant::Type type;
> 	QWidget* inner;
> public:
> 	ParameterInput ( QVariant::Type type = QVariant::Int, QWidget* parent  
> = 0 )
> 		: QWidget( parent ), type( type )
> 	{
> 		switch ( type )
> 		{
> 			case QVariant::Int:
> 				inner = new QSpinBox( ..., this );
> 				break;
> 			case ...:
> 			...
> 		}
> 	};
> 	QVariant value ()
> 	{
> 		switch ( type )
> 		{
> 			case QVariant::Int:
> 				return qobject_cast<QSpinBox*>( inner )->value();
> 			case ...:
> 			...
> 		}
>
> 	};
> };
>
> You could even later have a signal emitted on data change, and hook it  
> up to the corresponding slot of inner on its construction, etc.   
> Furthermore, you could add some other convenience methods, like  
> ParameterInput(QVariant v,QWidget* parent) and setValue(QVariant v)  
> and so forth.  All done with switch statements.
>
> Except for this idea:  Do all the widgets you're interested in using  
> have the value property equal to what you want?  If so, throw the  
> switch statements out the window and just use setProperty() and  
> getProperty() on the value property.
>
> Surely someone has done this somewhere already; I'm getting the  
> reinventing the wheel feeling.  Anyone?...anyone?...Bueller?
>
> Nathan
>   
-- 
Helge Preuss
Freelance Software Developer
+49 30 40 30 10 90
+49 177 2262 484
helge.preuss at gmx.net



More information about the Qt-interest-old mailing list