PDA

View Full Version : design help with QList in an interface



GuusDavidson
7th February 2011, 00:43
Hi,

I am new to using QT and am in need of some guidence.

I want to create an interface that returns a list of pointers to objects, and then the classes that implement this interface should be able to both set and get the objects in the list.

Where I am getting confused is that I want a general interface that allows me to be able to get any items from any of the derived classes.
I don't understand how I should be handling converting the specialized datatypes like
QList<newsChannelItem*> items; back via the interface
QList<QObject*> getItems();



class ChannelInterface
{
public:
virtual QList<QObject*> getItems() = 0;
}

classes that then implement this interface



class storeChannel : public QObject, public ChannelInterface
{
QList<storeChannelItem*> items;
public:
QList<QObject*> getItems(); // I want to be able to return a list of storeChannelItem's


class newsChannel : public QObject, public ChannelInterface
{
QList<newsChannelItem*> items;
public:
QList<QObject*> getItems(); // I want to be able to return a list of newsChannelItem's


I appreciate any help on this, as I am pretty stuck.

thanks in advance

Guus Davidson

tbscope
7th February 2011, 04:28
If both storeChannelItem and newsChannelItem are based on QObject, then just store a QObject in your storeChannel and newsChannel.
Otherwise, why won't you return a list of storeChannelItems and newsChannelItems via getItems() ?

helloworld
7th February 2011, 07:05
You could use templates:



template <typename T>
class ChannelInterface
{
public:
virtual QList<T*> getItems() = 0;
};

class storeChannelItem
{
// ...
};

class newsChannelItem
{
// ...
};

class storeChannel : public QObject, public ChannelInterface<storeChannelItem>
{
QList<storeChannelItem*> items;
public:
QList<storeChannelItem*> getItems();
};

class newsChannel : public QObject, public ChannelInterface<newsChannelItem>
{
QList<newsChannelItem*> items;
public:
QList<newsChannelItem*> getItems();
};


EDIT: Don't forget to define a virtual destructor in your interface also:



template <typename T>
class ChannelInterface
{
public:
virtual ~ChannelInterface() {}
virtual QList<T*> getItems() = 0;
};