简体   繁体   English

QVariant到QObject *

[英]QVariant to QObject*

I'm trying to attach a pointer to an QListWidgetItem , to be used in the slot itemActivated . 我正在尝试附加一个指向QListWidgetItem的指针,用于插槽itemActivated

The pointer I'm trying to attach is a QObject* descendant, so, my code is something like this: 我试图附加的指针是一个QObject*后代,所以,我的代码是这样的:

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. 现在我的问题, itemActivated插槽。 Here I need to extract my Image* from the variant, and I don't know how to. 在这里,我需要从变体中提取我的Image* ,我不知道如何。

I tried this, but I get the error: 我试过这个,但是我得到了错误:

'qt_metatype_id' is not a member of 'QMetaTypeId' 'qt_metatype_id'不是'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 . 这看起来像QVariant一个不寻常的用途。 I'm not even sure if QVariant would support holding a QObject or QObject* that way. 我甚至不确定QVariant是否支持以这种方式持有QObjectQObject* Instead, I would try deriving from QListWidgetItem in order to add custom data, something like this: 相反,我会尝试从QListWidgetItem派生以添加自定义数据,如下所示:

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. 此外,这个新类的析构函数为您提供了合理的逻辑,以确保您的Image得到清理。

You've inserted your Image class as QObject *, so get it out as QObject * also. 您已将Image类作为QObject *插入,因此也将其作为QObject *输出。 Then perform qobject_cast and everything should be fine 然后执行qobject_cast,一切都应该没问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM