tags:

views:

58

answers:

3

Hi, I'm trying to attach a pointer to an QListWidgetItem, to be used in the SLOT itemActivated.

The pointer I'm trying to attach is a QObject* descendant, so, my code is something like this:

Image * im = new Image();  
// here I add data to my Image object
// now I create my item
QListWidgetItem * lst1 = new QListWidgetItem(*icon, serie->getSeriesInstanceUID(),  m_iconView);
// then I set my instance to a QVariant
QVariant v(QMetaType::QObjectStar, &im)
// now I "attach" the variant to the item.
lst1->setData(Qt::UserRole, v);
//After this, I connect the SIGNAL and SLOT
...

Now my problem, the itemActivated SLOT. Here I need to extract my Image* from the variant, and I don't know how to.

I tried this, but I get the error: ‘qt_metatype_id’ is not a member of ‘QMetaTypeId’

void MainWindow::itemActivated( QListWidgetItem * item )
{
    Image * im = item->data(Qt::UserRole).value<Image *>();
    qDebug( im->getImage().toAscii() );
}

Any hint?

Image * im = item->data(Qt::UserRole).value();

+1  A: 

That looks like an unusual use of QVariant. I'm not even sure if QVariant would support holding a QObject or QObject* that way. Instead, I would try deriving from QListWidgetItem in order to add custom data, something like this:

class ImageListItem : public QListWidgetItem
{
  // (Not a Q_OBJECT)
public:
  ImageListItem(const QIcon & icon, const QString & text,
                Image * image,
                QListWidget * parent = 0, int type = Type);
  virtual ~ImageListItem();
  virtual QListWidgetItem* clone(); // virtual copy constructor
  Image * getImage() const;

private:
  Image * _image;
};

void MainWindow::itemActivated( QListWidgetItem * item )
{
     ImageListItem *image_item = dynamic_cast<ImageListItem*>(item);
     if ( !image_item )
     {
          qDebug("Not an image item");
     }
     else
     {
         Image * im = image_item->getImage();
         qDebug( im->getImage().toAscii() );
     }
}

Plus, the destructor of this new class gives you somewhere logical to make sure your Image gets cleaned up.

aschepler
Thanks aschepler for this nice and clean solution.
Leonardo M. Ramé
Sorry aschepler, this won't work. The SIGNALS are not emitted, how can I workaround this problem?
Leonardo M. Ramé
+1  A: 

You've inserted your Image class as QObject *, so get it out as QObject * also. Then perform qobject_cast and everything should be fine

Kamil Klimek
A: 

The answer is this

// From QVariant to QObject *
QObject * obj = qvariant_cast<QObject *>(item->data(Qt::UserRole));
// from QObject* to myClass*
myClass * lmyClass = qobject_cast<myClass *>(obj);
Leonardo M. Ramé
That's what i wrote...
Kamil Klimek
Nope, you wrote what to do, but I needed HOW TO DO IT.
Leonardo M. Ramé
I wrote how to do it
Kamil Klimek