Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QVariant to QObject*

Tags:

c++

qt4

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<Image *>();
like image 378
Leonardo M. Ramé Avatar asked Oct 08 '10 01:10

Leonardo M. Ramé


2 Answers

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);
like image 175
Leonardo M. Ramé Avatar answered Nov 04 '22 03:11

Leonardo M. Ramé


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.

like image 2
aschepler Avatar answered Nov 04 '22 03:11

aschepler