Grantlee  0.4.0
Generic type and template support

Generic type support

Grantlee offers powerful support for using any type or container in a QVariant as part of the Context. Although QObject based introspection based on Q_PROPERTY is the most convenient way to access properties on objects in the context, sometimes it is necessary to use classes which do not derive from QObject (and therefore can't have Q_PROPERTY macros) and where it would not be practical to create QObject wrappers around all related classes.

In such cases the metatype can be registered with Grantlee and an introspection method can be written.

// Non-QObject
class Person
{
public:
Person() :age(0) {}
Person(const QString &name, int age)
: m_name(name), m_age(age)
{
}
QString name() const
{
return m_name;
}
int age() const
{
return m_age;
}
private:
QString m_name;
int m_age;
};
// Make it possible to put Person in a QVariant.
Q_DECLARE_METATYPE(Person)
// Make it possible to put QList<Person> in a QVariant.
Q_DECLARE_METATYPE(QList<Person>)
// Read-only introspection of Person object.
if ( property == "name" )
return object.name();
else if ( property == "age" )
return object.age();
void someInitializer()
{
// Register the Person type with the %Grantlee introspection system.
Grantlee::registerMetaType<Person>();
}
Grantlee::Context getContext()
{
Person leader("The Leader", 19);
QList<Person> followers;
for (int i = 0; i < 3; ++i)
{
Person follower("Follower" + QString::number(i), 18);
people.append(follower);
}
c.insert("leader", QVariant::fromValue(leader));
c.insert("followers", QVariant::fromValue(followers));
return c;
}
QString createOutput()
{
Template t = m_engine->newTemplate(
"<h1>{{ leader.name }}</h1>"
"<ul>"
"{% for person in followers %}"
"<li>{{ person.name }}, {{ person.age }}</li>"
"{% endfor %}"
"</ul>"
);
Context c = getContext();
return t->render(&c);
}

There are several necessary steps and consequences.

Generic container support

Grantlee supports most Qt and stl containers by default if they are registered with the QMetaType system as shown in Generic type support. Where a container does not have built in support it can easily be added (See Third party containers).

The following containers have built in support:

where T is one of

Note that QSet<T> is an exception and will only work with types for which qHash(T) is defined. This means that QSet<QVariant> is not possible for example.

Note also that containers of pointers to QObject derived types can be stored in containers of QObject* (that is QVector<QObject*> instead of QVector<PersonObject*>), and they do not need to be explicitly registered with Grantlee. Where the class has sufficient Q_PROPERTYs defined, the introspection method described above with GRANTLEE_BEGIN_LOOKUP and GRANTLEE_END_LOOKUP is also not necessary. Note also that any type or container can be used through a Q_PROPERTY.

class PersonObject : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name)
Q_PROPERTY(int age READ age)
public:
PersonObject(const QString &name, int age, QObject *parent = 0);
QString name() const;
int age() const;
};
// Make it possible to put the containers in a QVariant
Q_DECLARE_METATYPE<QSet<QObject*>)
Q_DECLARE_METATYPE<std::vector<QObject*>)
class SportsClub : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name)
Q_PROPERTY(QString sport READ sport)
Q_PROPERTY(std::vector<QObject*> members READ members)
public:
SportsClub(const QString &name, const QString &sport, QObject *parent = 0);
QString name() const;
QString sport() const;
std::vector<QObject*> members() const;
void setMembers(std::vector<QObject*> members);
};
void someInitializer()
{
// QObject* already has built in support. No need to register the types
// with Grantlee::registerMetaType
}
Grantlee::Context SomeClass::getContext()
{
{
SportsClub *club = new SportsClub("Smithfield Tennis Club", "Tennis", this);
{
QObject *member = new PersonObject("Alice", 21, this);
members.push_back(member);
}
{
QObject *member = new PersonObject("Bob", 22, this);
members.push_back(member);
}
club.setMembers(members);
}
// ... specify other clubs and members
c.insert("sportsClubs", QVariant::fromValue(clubs));
return c;
}
QString createOutput()
{
Template t = m_engine->newTemplate(
"{% regroup sportsClubs by sport as groupedSports %}"
"{% for groupedClub in groupedSports %}"
"<h1>{{ groupedClub.grouper }}</h1>"
"{% for club in groupedClub.list %}"
"<h2>{{ club.name }}</h2>"
"<ul>"
"{% for member in club.members %}"
"<li>{{ member.name, }}, {{ member.age }}"
"{% endfor %}"
"</ul>"
"{% endfor %}"
"{% endfor %}"
);
Context c = getContext();
return t->render(&c);
}
See Also
The regroup tag

The output would be something like

  <h1>Tennis</h1>
    <h2>Smithfield Tennis Club</h2>
    <ul>
      <li>Alice, 21</li>
      <li>Bob, 22</li>
    </ul>
    <h2>Greenore Lawn Tennis and Fitness Club</h2>
    <ul>
      <li>Charlie, 23</li>
      <li>David, 24</li>
      <li>Elaine, 25</li>
      <li>Frank, 26</li>
    </ul>
  <h1>Basketball</h1>
    <h2>Sandyford Basketball Club</h2>
    <ul>
      <li>Gilian, 27</li>
      <li>Henry, 28</li>
    </ul>

Of course, it is possible to use containers of pointers to concrete QObject subclasses, such as QSet<PersonObject*> and std::vector<SportsClub*> but then it is necessary to register them with Grantlee using Grantlee::registerMetaType<PersonObject*>() and Grantlee::registerMetaType<SportsClub*>(). The use of GRANTLEE_BEGIN_LOOKUP and GRANTLEE_END_LOOKUP is still not required in that case.

Because any supported container can also be used as a contained type, nested containers are also supported.

Note that if a type is registered with Grantlee::registerMetaType, built in containers of that type do not also need to be registered. They will be registered automatically by Grantlee. Third party containers do need to be registered however (See Third party containers)

Q_DECLARE_METATYPE(Person)
Q_DECLARE_METATYPE(QVector<Person>)
Q_DECLARE_METATYPE(QList<QVector<Person> >)
Q_DECLARE_METATYPE(QStack<QList<QVector<Person> > >)
void someInitializer()
{
Grantlee::registerMetaType<Person>();
// Now any of the nested containers can be put in a Context and used in a Template.
}

Third party containers

To support another, non-built in container it is necessary to use some macros to register it with Grantlee.

For a sequential container, GRANTLEE_REGISTER_SEQUENTIAL_CONTAINER, GRANTLEE_SEQUENTIAL_TYPE_CONTAINER_ACCESSOR and GRANTLEE_REGISTER_SEQUENTIAL_CONTAINER_IF are needed.

#include <boost/circular_buffer>
// Enable looping over the contents of the container
// Enable operator[] index lookup in the container.
Q_DECLARE_METATYPE(boost::circular_buffer<Person>)
Q_DECLARE_METATYPE(boost::circular_buffer<SportsClub>)
void someInitializer()
{
Grantlee::registerMetaType<Person>();
// Make it possible to use circular_buffer<Person> and Container<circular_buffer<Person> >
// for any built in Container.
GRANTLEE_REGISTER_SEQUENTIAL_CONTAINER_IF(boost::circular_buffer, Person)
// Make it possible to use circular_buffer<SportsClub> and Container<circular_buffer<SportsClub> >
// for any built in container.
GRANTLEE_REGISTER_SEQUENTIAL_CONTAINER_IF(boost::circular_buffer, SportsClub)
}
Grantlee::Context getContext()
{
boost::circular_buffer<Person> buffer(5);
// loop
{
Person p("Grant", 21);
b.push_back(p);
}
c.insert("people", QVariant::fromValue(buffer));
}

Note that if the container does not allow operator[] lookup it is necessary to use the GRANTLEE_DISABLE_RANDOM_ACCESS macro instead of GRANTLEE_SEQUENTIAL_TYPE_CONTAINER_ACCESSOR

#include <ext/slist>
// Enable looping over the contents of the container
// Disable operator[] index lookup in the container.

This means that template constructs such as {{ someList.4 }} will work for containers with operator[], such as QList and QVector, but will not work with containers like QLinkedList, QSet, std::list.

See Also
Variable lookups

For associative containers GRANTLEE_REGISTER_ASSOCIATIVE_CONTAINER, GRANTLEE_ASSOCIATIVE_TYPE_CONTAINER_ACCESSOR and GRANTLEE_REGISTER_ASSOCIATIVE_CONTAINER_IF are needed.

It might also be necessary, depending on the API of the container to define additional accessors for keys and values from a const_iterator. By default, Grantlee uses iter.key() and iter.value() (The Qt default) to access them. Grantlee::KeyGetter and Grantlee::MappedValueGetter can be specialized for custom access. Note that they must be defined in the Grantlee namespace

namespace {
// Make it possible to put Qt types in a std::hash_map
template <typename Key>
struct QtHasher
{
size_t operator()(Key k) const
{ return qHash(k); }
};
// std::hash_map capable of storing Qt types.
template<typename Key, typename Value>
struct QtHashMap : public std::hash_map<Key, Value, QtHasher<Key> >
{
};
}
// Register the container with Grantlee
namespace Grantlee {
// Specialize for getting the key from the iterator
template<typename T, typename U>
struct KeyGetter<QtHashMap<T, U> > : public Getter<QtHashMap<T, U> >
{
static T get(typename QtHashMap<T, U>::const_iterator it)
{
return it->first;
}
};
// Specialize for getting the value from the iterator
template<typename T, typename U>
struct MappedValueGetter<QtHashMap<T, U> > : public Getter<QtHashMap<T, U> >
{
static U get(typename QtHashMap<T, U>::const_iterator it)
{
return it->second;
}
};
}

Smart Pointers

Shared pointer types containing a custom type should be introspected as normal using GRANTLEE_BEGIN_LOOKUP and GRANTLEE_END_LOOKUP

Q_DECLARE_METATYPE(QSharedPointer<Person>)
void someInitializer()
{
Grantlee::registerMetaType<QSharedPointer<Person> >();
}
if (property == "name")
return object->name();

Note that if only shared pointers to the type is in your introspectable API you only need to define the property access for the shared pointer. In the case above, there is no need to use Q_DECLARE_METATYPE or GRANTLEE_BEGIN_LOOKUP with Person or Person*.

This is of course true of any smart pointer:

Q_DECLARE_METATYPE(boost::shared_ptr<Person>)
GRANTLEE_BEGIN_LOOKUP(boost::shared_ptr<Person>)
if (property == "name")
return object->name();

QSharedPointers containing QObject derived types get special treatment.

QObjects are automatically introspected for their Q_PROPERTYs (See Custom objects).

If you have QSharedPointer<PersonObject> where PersonObject is derived from QObject it will be automatically introspected just like a QObject* is without requiring the GRANTLEE_BEGIN_LOOKUP and GRANTLEE_END_LOOKUP macros.

Q_DECLARE_METATYPE(QSharedPointer<PersonObject>)
void someInitializer()
{
Grantlee::registerMetaType<QSharedPointer<PersonObject> >();
}
void getContext()
{
QSharedPointer<PersonObject> p( new PersonObject );
c.insert("person", QVariant::fromValue(p));
return c;
}
QString createOutput()
{
// Uses Q_PROPERTYs defined on PersonObject for name and age
Template t = m_engine->newTemplate( "{{ person.name }}, {{ person.age }}" );
Context c = getContext();
return t->render(&c);
}

Note that Grantlee::registerMetaType must be used for the specialized shared pointer type.

The same technique can be used to support QObject derived types in third party shared pointers, but that requires an extra macro, GRANTLEE_SMART_PTR_ACCESSOR.

Q_DECLARE_METATYPE(boost::shared_ptr<PersonObject>)
GRANTLEE_SMART_PTR_ACCESSOR(boost::shared_ptr)
void someInitializer()
{
Grantlee::registerMetaType<boost::shared_ptr<PersonObject> >();
}
void getContext()
{
boost::shared_ptr<PersonObject> p( new PersonObject );
c.insert("person", QVariant::fromValue(p));
return c;
}