Mircea
Mircea

Reputation: 1999

Qt C++ Custom QWidget with Templates

I've trying to combine a Custom QWidget which should contain some Template parameter insider, but I don't know how to do this because I'm not allowed by the Qt.

My Template Class:

template<typename T>
struct AbstractData {
    QWidget* displayedItem{};
    T* data;
};

Now what I'm trying to do it's to create a custom Widget like a QScrollArea (similar, not the same). But when someone will click on one element I want to emit a signal which will contain that data structure which the user had provide.

For example:

template<typename T>
class PlaylistController : public QWidget {
Q_OBJECT

private:
    QLayout *m_layout{};

    std::vector<AbstractData<T> *> m_vecAbsData{};
    std::vector<DelegateItem *> m_items{};

public:
    explicit PlaylistController(QWidget *parent = nullptr);

protected:
    void paintEvent(QPaintEvent *event) override;

    void wheelEvent(QWheelEvent *event) override;

signals:
    void clicked(T elem);

public slots:
    void loadElements(const std::vector<AbstractData<T> *> &elements);
};

Here the m_vecAbsData consists of AbstractData which will contain the QWidget that I want to display on screen as on element (because I will have a list where you can scroll between elements). And also the T is going to be whatever data the user wants.

Is there any way in which I can obtain what I wanned? Because so far the QT is going to send me an error message:

Error: Template classes not supported by Q_OBJECT

How can I combine Templates and QWidget in such a way that I can emit a signal with a data type T which can be anything?

I know about the answer from here but I can't do that because I don't know what kind of data my user wants to use. Is there any workaround?

Upvotes: 0

Views: 1216

Answers (1)

JarMan
JarMan

Reputation: 8277

How can I combine Templates and QWidget in such a way that I can emit a signal with a data type T which can be anything?

You can't. The moc needs a completely defined type. There's a pretty good explanation here.

You can have template classes derive from QObjects as long as they don't use signals or slots in the template. It would looks something like this:

class SomeBase : public QObject 
{
    Q_OBJECT
...
signals:
    void someSignal();
};

template<class T>
class SomeTemplate : SomeBase
{
// Don't use Q_OBJECT macro
// Don't use signals or slots
};

Upvotes: 1

Related Questions