0

Consider the following minimal example:

namespace foo { struct MyStruct {}; }
Q_DECLARE_METATYPE(foo::MyStruct)

namespace bar { struct MyStruct {}; }
Q_DECLARE_METATYPE(bar::MyStruct)

// later on near the entry point of the program:

qRegisterMetaType<foo::MyStruct>("MyStruct");
qRegisterMetaType<bar::MyStruct>("MyStruct");

This code potentially leads to a crash. When a slot is invoked that accepts const foo::MyStruct& as an argument, Qt's meta object system provides const bar::MyStruct& instead due to alias ambiguity.

I know that the obvious fix is to change MyStruct's name to something else to avoid the clash entirely. The problem there is that I suspect I shouldn't have to do that, and under certain conditions I may not even be able to do that (imagine both structs provided by independent plugins that are unaware of each other).

That being said, I have a couple of questions:

  1. I tried changing both aliases to contain namespace qualifiers, e.g. qRegisterMetaType<foo::MyStruct>("foo::MyStruct"), but then Qt silently behaves as if I had not registered the meta type at all. This seems like a clean solution to me. Why is that not permitted? And why do I get no warnings?

  2. If I do a twist on the previous approach and change the aliases to something like foo_MyStruct, fooMyStruct or MyStruct2, or even do not pass any alias to the function, this doesn't seem to work either. Does the alias argument have to be present and match the symbol name exactly?

  3. What other options do I have? (short of renaming the structs)

Cheers!

Petr Mánek
  • 1,046
  • 1
  • 9
  • 24
  • Maybe this is useful: https://stackoverflow.com/questions/22044737/when-where-and-why-use-namespace-when-registering-custom-types-for-qt ? – alagner May 19 '21 at 08:05
  • @alagner This is a good post but I'm not really sure it answers my question. According to it, the following should work (but doesn't): `qRegisterMetaType("foo::MyClass");` – Petr Mánek May 19 '21 at 08:24
  • I wonder if your problem specific to QT6 (as tag suggests)? No clue at the moment, but if so: maybe sth has changed in the internals? If not - simple answer is that QT uses strings to handle the metainfo (which you probably already know) and there seems to be a clash in naming. – alagner May 19 '21 at 08:31
  • @alagner I don't think the bug is _specific to Qt6_ as I encountered this behavior in Qt5 as well but I'm currently using Qt6, which is why used the tag. I know about strings & Qt's meta types. What puzzles me is that some string aliases seem to be allowed, whereas others just fail silently (which looks horrifying). And thus far, I found no authoritative explanation in Qt docs. – Petr Mánek May 19 '21 at 08:37

0 Answers0