I have two QVariantMap
instances A and B.
In A I have the following strings: [ "key1" => "Cat", "key2" => "Dog", "key3" => "Mouse" ]
.
In B I have the following strings: [ "key1" => "Cat", "key4" => "Dog", "key3" => "Bison" ]
.
I want to merge them into a third QVariantMap
instance C so that it contains the following:
[ "key1" => "Cat", "key2" => "Dog", "key3" => "Bison", "key4" => "Dog" ]
.
Note how there is only one "Cat" and how "Mouse" was replaced by "Bison".
Is there a way to do this in Qt5 without writing my own utility function to do it?
Since 5.15, Qt provides an insert
overload taking another QMap
as parameter, which inserts all key/value pairs from the other map into the original map, overwriting existing keys:
QVariantMap A;
QVariantMap B;
A.insert("key1", "Cat");
A.insert("key2", "Dog");
A.insert("key3", "Mouse");
B.insert("key1", "Cat");
B.insert("key4", "Dog");
B.insert("key3", "Bison");
QVariantMap C(A);
C.insert(B);
// C now holds the combined keys&values of A & B;
// for keys existing in both A and B, the values from B are taken!