开发者

QVariant to QObject*

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->getSe开发者_如何学GoriesInstanceUID(),  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 *>();


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);


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜