Skip to content
Permalink
Browse files

Still allow custom meta types for Q_GADGETs

This is relevant when trying to make Q_GADGETs accessible that come from
a library that you can't easily extend by Q_PROPERTY, and restores
behavior compatibility with pre-Q_GADGET support.
  • Loading branch information...
vkrause committed Aug 30, 2019
1 parent caa5be7 commit 0899b37aeca712f28ebaf9a544afce8ddc4a419c
Showing with 36 additions and 4 deletions.
  1. +3 −4 templates/lib/metatype.cpp
  2. +33 −0 templates/tests/testgenerictypes.cpp
@@ -178,11 +178,10 @@ QVariant Grantlee::MetaType::lookup(const QVariant &object,
QMetaType mt(object.userType());
if (mt.flags().testFlag(QMetaType::IsGadget)) {
const auto idx = mo->indexOfProperty(property.toUtf8().constData());
if (idx < 0) {
return QVariant();
if (idx >= 0) {
const auto mp = mo->property(idx);
return mp.readOnGadget(object.constData());
}
const auto mp = mo->property(idx);
return mp.readOnGadget(object.constData());
}
}

@@ -78,6 +78,7 @@ private Q_SLOTS:
void testUnregistered();
void testPointerNonQObject();
void testQGadget();
void testGadgetMetaType();

}; // class TestGenericTypes

@@ -98,9 +99,19 @@ class Person
int uid;
};

class PersonGadget
{
Q_GADGET
Q_PROPERTY(QString name MEMBER m_name)
public:
QString m_name;
int m_age = 42;
};

int qHash(const Person &p) { return p.uid; }

Q_DECLARE_METATYPE(Person)
Q_DECLARE_METATYPE(PersonGadget)

GRANTLEE_BEGIN_LOOKUP(Person)
if (property == QStringLiteral("name"))
@@ -109,6 +120,11 @@ else if (property == QStringLiteral("age"))
return object.age;
GRANTLEE_END_LOOKUP

GRANTLEE_BEGIN_LOOKUP(PersonGadget)
if (property == QStringLiteral("age"))
return object.m_age;
GRANTLEE_END_LOOKUP

class PersonObject : public QObject
{
Q_OBJECT
@@ -132,6 +148,7 @@ void TestGenericTypes::initTestCase()
{
// Register the handler for our custom type
Grantlee::registerMetaType<Person>();
Grantlee::registerMetaType<PersonGadget>();
}

void TestGenericTypes::testGenericClassType()
@@ -806,6 +823,22 @@ void TestGenericTypes::testQGadget()
QCOMPARE(result.value<int>(), 42);
}

void TestGenericTypes::testGadgetMetaType()
{
Grantlee::Engine engine;
engine.setPluginPaths({QStringLiteral(GRANTLEE_PLUGIN_PATH)});

auto t1 = engine.newTemplate(
QStringLiteral("Person: \nName: {{p.name}}\nAge: {{p.age}}"),
QStringLiteral("template1"));

PersonGadget p;
p.m_name = QStringLiteral("Some Name");
Grantlee::Context c;
c.insert(QStringLiteral("p"), QVariant::fromValue(p));
QCOMPARE(t1->render(&c), QStringLiteral("Person: \nName: Some Name\nAge: 42"));
}

class ObjectWithProperties : public QObject
{
Q_OBJECT

0 comments on commit 0899b37

Please sign in to comment.
You can’t perform that action at this time.