QVariant转换为QObject*

14

我想将一个指针附加到QListWidgetItem上,以在槽itemActivated中使用。

我尝试附加的指针是一个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
...

现在我的问题是,itemActivated槽函数。在这里,我需要从变量中提取我的Image*对象,但我不知道该怎么做。

我尝试了以下代码,但是出现了错误:

‘qt_metatype_id’ 不是 ‘QMetaTypeId’ 的成员

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

有什么提示吗?

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

1
根据QVariant(int typeId, const void *copy)构造函数的文档:“通常情况下,您不需要使用此构造函数,而应改为使用QVariant::fromValue()从由QMetaType::VoidStar和QMetaType :: QObjectStar表示的指针类型构造变量。” - Andreas Haferburg
请注意,&im 的类型是 Image**,而不是 Image* - Andreas Haferburg
3个回答

29
答案如下。
// From QVariant to QObject *
QObject * obj = qvariant_cast<QObject *>(item->data(Qt::UserRole));
// from QObject* to myClass*
myClass * lmyClass = qobject_cast<myClass *>(obj);

6
不行,你写了要做什么,但我需要如何去做。 - Leonardo M. Ramé
1
为什么不使用 qvariant_cast 直接转换为 myClass*?像这样:myClass * lmyClass = qvariant_cast<myClass *>(item-data(Qt::UserRole)); - Ignitor
没关系:看了qvariant_cast的实现后,让我明白了原因:qvariant_cast的类型参数必须(应该?)为元对象系统所知。 - Ignitor

2

这似乎是对 QVariant 的不寻常使用。我甚至不确定 QVariant 是否支持以这种方式保存 QObjectQObject*。相反,我建议从 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() );
     }
}

此外,这个新类的析构函数为您提供了一个逻辑位置来确保您的Image得到清理。

感谢aschepler提供这个漂亮而简洁的解决方案。 - Leonardo M. Ramé
抱歉,aschepler,这样做行不通。SIGNALS没有被发射,我该如何解决这个问题? - Leonardo M. Ramé

0
你已将你的Image类插入为QObject*,所以也要将它作为QObject*取出。然后执行qobject_cast就可以了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接