[Qt-interest] Making a template class a Q_OBJECT

BRM bm_witness at yahoo.com
Wed Dec 16 01:20:53 CET 2009


Qt doesn't support templates; but here's the trick to do some templatization. It doesn't work for every scenario but should be good enough.

1) Define you class as a normal, non-Qt C++ template. You can't use any signals/slots/etc.
template<typeName T>
class myTemplateClass
{
....
};

2) Define an instance of the template via a typedef

typedef myTemplateClass<someInstance> myTemplateClassSomeInstance;

Now you have a choice (though I think I know which one the Qt guys will favor):

A) Derive a dual inheritance class from both the template instance (#2 above) and QObject
B) Make a QObject that has a private variable of the templated type.

In either case, the class will have to have the appropriate methods defined, some of which you could make out as SLOTS.
Signals are a bit harder, though you could probably do it with 'A' if you defined some virtual functions - 
e.g. /* virtual */ void doSignalA() { Q_EMIT signalA(); }


You could probably do the same with B using function pointers, but it gets a little messier.

>From what I've seen and read I think there will likely be a good deal of the 'do B'.

But either implementation should work so long as QObjects just can't have multiple inheritance with another QObject (which I think is the primary reason behind the no-multiple-inheritance-in-qt).

2 cents for the pot.

Ben


----- Original Message ----
From: John Clayton <johnclayton72 at gmail.com>
To: qt-interest <qt-interest at trolltech.com>
Sent: Tue, December 15, 2009 6:09:52 PM
Subject: [Qt-interest] Making a template class a Q_OBJECT

Hi All

I'm wondering how I can make my template class a Q_OBJECT type.

I've got a template, defined like this:

template<typename T = QGraphicsObject>
class PreviewGraphicsItem : public T, // must be some kind of QObject
            public PreviewBase,
            public ControlPoint::Delegate
{

// Q_OBJECT
// the above line will cause compiler errors - wonder what the work- 
around is?

public:
    // magic stuff goes here...
};


What I really want to do is put a Q_OBJECT decl just above the public:  
access specifier, but that doesn't work (compiler complains bitterly).

The class defines common functionality for an object that sits in a  
preview window (within a graphics scene).  It will always have a  
template parameter that is derived from QObject.

The reason I want to put the Q_OBJECT macro in there, is because I'd  
like to implement Q_PROPERTY statements at this level in the hierarchy.

Your ideas are appreciated,

Thanks
--
John Clayton


_______________________________________________
Qt-interest mailing list
Qt-interest at trolltech.com
http://lists.trolltech.com/mailman/listinfo/qt-interest





More information about the Qt-interest-old mailing list