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

Tom Isaacson Tom.Isaacson at navico.com
Wed Jul 3 22:25:54 CEST 2019


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?

Tom Isaacson



More information about the Development mailing list