14 окт. 2008 г.

Qt4: Usage C++ templates with Q_OBJECT

There is a problem to use C++ template class which should have Q_OBJECT macros.

Using the Meta-Object Compiler (moc):
moc doesn't create moc class (qt meta info for class) for follow class declaration :
template <class T>
class SomeWidget : public SomeSubWidget {
Q_OBJECT
public:
SomeWidget(QWidget *parent = 0): SomeSubWidget(parent){
}
// for instance, wrap T class
protected:
virtual T* component(QWidget *parent = 0) { return new T(parent); }

T *widget;
};


Solution: devide class for two classes - with Q_OBJECT declaration and with template:
create sub class with Q_OBJECT
class SomeSubWidget : public QWidget
{
Q_OBJECT
public:
SomeSubWidget(QWidget *parent = 0):QWidget(parent){}
};

and when inherit it and add template:
template <class T>
class SomeWidget : public SomeSubWidget
{
public:
SomeWidget(QWidget *parent = 0): SomeSubWidget(parent){
}
// for instance, wrap T class
protected:
virtual T* component(QWidget *parent = 0) { return new T(parent); }

T *widget;
};


Reference article: Academic Solutions to Academic Problems
Почему в Qt для сигналов и слотов не используются шаблоны

1 комментарий:

Анонимный комментирует...

http://doc.qt.digia.com/qq/qq15-academic.html

http://stackoverflow.com/questions/4397478/qt-templated-q-object-class