QHash in QList in QHash
-
Basically I was wondering if it is possible to put a QHash in a QList which I then put in a QHash.
This is my code:
@ QHash<QString, QVariant> info;
info.insert("someinfo", "blah blah"); info.insert("moreinfo", 123456); QList<QHash<QString, QVariant> > list; QHash<QString, QVariant> blah; blah.insert("some", "stuff"); list << blah; info.insert("somelist", list);@
But the last line (14) obviously gives me an error as I do not know the proper way to approach this.
@error: no matching function for call to 'QHash<QString, QVariant>::insert(const char [9], QList<QHash<QString, QVariant> >&)'
candidates are: QHash<Key, T>::iterator QHash<Key, T>::insert(const Key&, const T&) [with Key = QString, T = QVariant]@
Any ideas?
Thanks in advance.
-
Try this:
@
info.insert("somelist", QVariant::fromValue(list));
@ -
[quote author="Krzysztof Kawa" date="1358076526"]Try this:
@
info.insert("somelist", QVariant::fromValue(list));
@[/quote]Tried but didnt work. I think we need to register using Q_DECLARE_METATYPE for the list but that too didn't work.
-
Just tried this and it prints "bar" as expected:
@
#include <QDebug>
#include <QList>
#include <QHash>
#include <QVariant>
#include <QString>int main()
{
QHash<QString, QVariant> hash;
hash["foo"] = "bar";QList<QHash<QString, QVariant> > list; list << hash; QHash<QString, QVariant> hash2; hash2.insert("buzz", QVariant::fromValue(list)); QList<QHash<QString, QVariant> > bar; bar = hash2["buzz"].value<QList<QHash<QString, QVariant> > >(); qDebug() << bar[0]["foo"].toString(); return 0;
}
@ -
Or... be a man and use typedefs :P
-
[quote author="utcenter" date="1358092235"]Or... be a man and use typedefs :P [/quote]
Well sure, in a production code. But the point here was to show it actually works with those types, thus the overly verbose syntax.
-
^^I didn't mean you but the OP, your example is perfectly adequate.
Even if for some reason it is necessary to put a hash in a list in a hash, doing so with the raw containers themselves is not something I would consider a good practice, it is much better to build up this kind of structure with typedefs, wrapper classes and accessor methods to make the whole process with working with this transparent.
-
Okay, now I've managed to store it with the following code:
@ QVariantHash info;
info.insert("someinfo", "blah blah"); info.insert("moreinfo", 123456); // QVariantList list; QVariantHash blah; blah.insert("some", "stuff"); list << blah; info.insert("somelist", list); // QVariantHash myHash = info["somelist"].toList().at(0).toHash(); qDebug() << myHash["some"].toString(); // outputs "stuff"@
Is there any "nicer" way of doing this?
EDIT: I'm new to both C++ and Qt so I pretty much have no idea what I am doing, just playing around. :P