[Development] Why does Q_ENUM() need qRegisterMetaType()?

Olivier Goffart olivier at woboq.com
Thu Jul 4 10:55:53 CEST 2019


On 03.07.19 22:25, Tom Isaacson wrote:
> No response on Qt Interest so trying here.
> 
> I'm using Qt 5.12.2 on Visual Studio 2019 / Win7. I wanted to make sure Q_ENUM works the way I think it does before updating some legacy code so I wrote a unit test (we use Google Test):
> 
> TestConnectEnum.h:
> 
> class tColoredObjectV3 : public QObject
> {
> 	Q_OBJECT
> 
> public:
> 	enum class eColor
> 	{
> 		Red = 1,
> 		Blue = 2,
> 		Green = 3
> 	};
> 	Q_ENUM(eColor)
> 
> 	tColoredObjectV3() : m_color(tColoredObjectV3::eColor::Red) {}
> 
> 	void EmitColor(tColoredObjectV3::eColor color);
> 
> signals:
> 	void ColorSignal(tColoredObjectV3::eColor color);
> 
> private:
> 	eColor m_color;
> };
> 
> TestEnumConnect.cpp:
> 
> TEST(Connect, ConnectEnumSucceedsV3)
> {
> 	//qRegisterMetaType<tColoredObjectV3::eColor>();
> 
> 	tColoredObjectV3 coloredObject;
> 
> 	QSignalSpy spy(&coloredObject, &tColoredObjectV3::ColorSignal);
> 	coloredObject.EmitColor(tColoredObjectV3::eColor::Blue);
> 
> 	EXPECT_TRUE(spy.isValid());
> 	EXPECT_EQ(spy.count(), 1); // make sure the signal was emitted exactly one time
> 	QList<QVariant> arguments = spy.takeFirst(); // take the first signal
> 	ASSERT_FALSE(arguments.isEmpty());
> 	tColoredObjectV3::eColor color = arguments.at(0).value<tColoredObjectV3::eColor>();
> 	EXPECT_EQ(tColoredObjectV3::eColor::Blue, color); // verify the first argument }
> 
> But this fails - I have to uncomment the qRegisterMetaType() to get it to work. If I use the old Q_DECLARE_METATYPE() this works. Am I doing something wrong or does Q_ENUM() require this?


The problem is that moc only generates the code that calls qRegisterMetaType if 
it sees Q_DECLARE_METATYPE. Actually, it does a bit more than that. It could as 
well do it for Q_ENUM type, just not implemented yet.

We should consider doing it for all the types used in signals/slots/properties. 
  But it does not do it because that could be a potential breaking change for 
forward declared types.
Maybe something for Qt6.

-- 
Olivier

Woboq - Qt services and support - https://woboq.com - https://code.woboq.org


More information about the Development mailing list