PDA

View Full Version : How to store and retrieve a simple int array int/from QVariant.-



tonnot
21st September 2011, 20:03
I need to use Qvariant to store and retrieve a simple int array. I can't....
I have declare an int * my_array;

If I use vv.value<int*>();
I have qt_metatype_id' is not a member of 'QMetaTypeId<int*>'

Any help ? Thanks

wysota
21st September 2011, 20:12
"int*" is "address of an int value". Do you really want to store a pointer in the variant? If so, then remember that an address is also a number and you can treat it as one and tell QVariant to treat it as one as well. Not an elegant solution but it will work.

tonnot
21st September 2011, 20:20
But int * my_array and my_array = new int[5] .....
I'd can use a fixed or dynamc int array, simply I was testing how to get that the QVariant gives me the value...

I'm unable to store and retrieve a simple int[5] . into/from a Qvariant .....
Can you help me?
Thanks

wysota
21st September 2011, 20:25
But int * my_array and my_array = new int[5] .....
I don't really want to teach you C++ right now. Get a book and read it.


Can you help me?
I already told you, treat the address as an integer, QVariant can accept those.

tonnot
21st September 2011, 20:35
Ok, I'm going to try it

ChrisW67
22nd September 2011, 00:29
QVariant will accept a void*, so if you are willing to discard type safety:


int *my_array = new int[5];

QVariant v1 = QVariant::fromValue( static_cast<void *>(my_array) );
int *p1 = static_cast<int*>( v1.value<void*>() );

delete[] my_array;

or, you can declare int* to the meta-type system:


Q_DECLARE_METATYPE(int*)

// and then
QVariant v2 = QVariant::fromValue(my_array);
int *p2 = v2.value<int*>();


Before you run off passing the pointer... you are passing a pointer to a block of memory (that might not exist) without passing the size of the block. How is the receiver supposed to know how many elements (ints in this case) can be safely accessed through that pointer?

Have you considered using QVector<int>?


Q_DECLARE_METATYPE(QVector<int>)

QVector<int> my_array(5);
QVariant v3 = QVariant::fromValue(a);
QVector<int> a = v3.value<QVector<int> >();
qDebug() << a.size();

This will copy the data if you modify the data at the receiving end but for read-only purposes is quite efficient.

tonnot
22nd September 2011, 07:05
Thank you very much !!!
A very vell explanation !