Thalia Thalia - 3 months ago 16
C++ Question

Build errors when iterating through QGraphicsItem items

I have changed my class Item to inherit from QGraphicsItem, and suddenly getting problems...

class Item : public QGraphicsItem
{
Item();
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget);
};

class CollectionView : public QGraphicsView
{
Q_OBJECT
public:
CollectionView(QWidget *parent = 0);
QList<Item> *m_items;
};

class ShapeView : public QGraphicsView
{
Q_OBJECT
public:
ShapeView(QWidget *parent = 0);
CollectionView *collectionView;
private:
void doWork();
};

void ShapeView::doWork()
{
outputView1->m_items->clear();
foreach (Item item, collectionView->m_items)
// for(int i = 0; i< collectionView->m_items->size(); i++)
{
// Item item = collectionView->m_items->at(i);
...
}
}


Either the for loop or the foreach, give me errors (were fine before inheriting from QGraphicsItem):

These errors if I use foreach:
'QList<Item>*' is not a class, struct, or union type
'class QForeachContainer<QList<Item>*>' has no member named 'i'
'class QForeachContainer<QList<Item>*>' has no member named 'e'
'class QForeachContainer<QList<Item>*>' has no member named 'i'
'class QForeachContainer<QList<Item>*>' has no member named 'i'
using invalid field 'QForeachContainer<T>::i'
request for member 'begin' in '((QForeachContainer<QList<Item>*>*)this)->QForeachContainer<QList<Item>*>::c', which is of non-class type 'QList<Item>* const'
using invalid field 'QForeachContainer<T>::e'
...
In copy constructor 'Item::Item(const Item&)':
'QGraphicsItem::QGraphicsItem(const QGraphicsItem&)' is private
within this context
In member function 'void ShapeView::doWork()':
synthesized method 'Item::Item(const Item&)' first required here
In member function 'Item& Item::operator=(const Item&)':
'QGraphicsItem& QGraphicsItem::operator=(const QGraphicsItem&)' is private

These errors if I use for loop: I only get:
In copy constructor 'Item::Item(const Item&)':
'QGraphicsItem::QGraphicsItem(const QGraphicsItem&)' is private
within this context
In member function 'void ShapeView::doWork()':
synthesized method 'Item::Item(const Item&)' first required here
In member function 'Item& Item::operator=(const Item&)':
'QGraphicsItem& QGraphicsItem::operator=(const QGraphicsItem&)' is private


What am I doing wrong, and what do these errors mean, and how can I fix them ?

Answer

This is the relevant part :

In copy constructor 'Item::Item(const Item&)':
'QGraphicsItem::QGraphicsItem(const QGraphicsItem&)' is private
within this context

You're inheriting from QGraphicsItem and you need to be copy-contructible, but QGraphicsItem isn't copyable.

The copy constructor of Item is needed for the foreach in ShapeView::doWork(), so you'll have to either write that function differently and explicitely delete your copy constructor, or find a way to define a valid cctor. The same goes for operator=.