PDA

View Full Version : Store QWeakPointers in QSet



salcin
22nd August 2013, 16:07
Hi,

I'm trying to store QWeakPointers in a QSet with no success. The compiler first complained about QWeakPointer is lacking a qHash function. I Implemented a qHashFunction, the project compiled but I can't fetch data from the QSet (tried iterators). It only returns invalid QWeakPointers.

Basically I'm trying to do:

QSet<QWeakPointer<MyClass> > oneSet;
QSharedPointer<MyClass> > myClass(new MyClass);
oneSet.insert(oneSet.toWeakRef());

for (QSet<QWeakPointer<MyClass> >::iterator it = oneSet.begin(); it != oneSet.end(); it++)
{
// do stuff
}


//My qHash:
template<typename T>
uint qHash(const QWP<T> &p)
{
return qHash(p.data()); //use the pointer a a key.
}

Does anyone have a solution for this?

high_flyer
22nd August 2013, 16:50
Can you explain what the following line is supposed to do?

oneSet.insert(oneSet.toWeakRef());

salcin
22nd August 2013, 17:03
That is a typo. It should be:


oneSet.insert(myClass.toWeakRef());


I chose to use QLinkedList instead of QSet. But I think I found the problem was. I believe that the qHash function was working, but I forgot to keep a QSharedPointer to the created objects. When the QSharedPointer went out of scope all the newly created objects were deleted, and only left the weak pointers behind. When I tried to iterate the list it couldn't promote the weak pointer to a strong pointer.

wysota
22nd August 2013, 17:55
Why not have a QList<QSharedPointer<MyClass> >?

salcin
22nd August 2013, 18:00
I need to have QWeakPointer because of cyclic reference. MyClass holds a QSharedPointer to a child MyClass and a QWeakPointer to a parent MyClass.

wysota
22nd August 2013, 18:11
And where is this cyclic reference?