PDA

View Full Version : Link QVariant to global variable



jobrandt
7th May 2007, 10:37
I have list of properties. Each property has a name and a QVariant value. I can access each property over the name(like QSettings).
I want to connect some property to a concrete global variable. If the value of property is changed the global variable should also be changed.
Here is some code to to show what i mean.


// global variable
double xy; // could be any other type (e.g int,QPoint,QString etc.)

class Prop
{
private:
QString mName;
QVariant mValue;
QVariant /*or void?? */ *mPointer; // should point to xy

public:
void SetPointer(/*Pointer to xy*/)
{
mPointer = /*Pointer to xy*/;
}

void SetGlobalVariabel()
{
// should set xy indirect with mPointer
*/*Pointer to xy*/ = mValue.value();
}
};

Is this possible? If yes, how can i do this.
There are other ways to change the global variable. But also this way should work.

wysota
7th May 2007, 10:47
If the global variable was also of type QVariant then this would be easy, but if you want to allow a generic type without QVariant, you have to provide some kind of "handlers" for different types and associate them with each global var. It'd be much easier if you used QVariant ;)

jobrandt
8th May 2007, 10:18
Now i have solved the problem with a handler:


// global variable
double xy; // could be any other type (e.g int,QPoint,QString etc.)

class Prop
{
private:
QString mName;
QVariant mValue;
void *mPointer; // should point to xy

public:
void SetPointer(void *pointer)
{
mPointer = pointer;
}

void SetGlobalVariabel() // should set xy indirect with mPointer
{
if (!mPointer) return;

switch (mValue.type())
{
case (QVariant::Double): {
*(static_cast<double*>(mPointer)) = mValue.value<double>();
break;
}
case (QVariant::Int): {
*(static_cast<int*>(mPointer)) = mValue.value<int>();
break;
}
default:
;
}
}
};
SetPointer(&xy) links the QVariant variable to the global variable.
SetGlobalVariable() sets the global variable.

This is not exactly what i wanted but since i only need some types of QVariant it is the fastest way to solve the problem.

A more common solution should be possible if i would know the address(pointer) where QVariant stores the value of the variable.

But at the moment the problem is solved for me.

Thanks for the help.