QVariant 到 QObject*
我正在尝试将指针附加到 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 *>();
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 *>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
答案是这样的
The answer is this
这看起来像是 QVariant 的不寻常用法。我什至不确定 QVariant 是否支持以这种方式保存 QObject 或 QObject* 。相反,我会尝试从
QListWidgetItem
派生,以便添加自定义数据,如下所示:另外,这个新类的析构函数为您提供了逻辑上的地方,以确保您的
Image
被清理干净。That looks like an unusual use of
QVariant
. I'm not even sure ifQVariant
would support holding aQObject
orQObject*
that way. Instead, I would try deriving fromQListWidgetItem
in order to add custom data, something like this:Plus, the destructor of this new class gives you somewhere logical to make sure your
Image
gets cleaned up.您已将 Image 类作为 QObject * 插入,因此也将其作为 QObject * 取出。然后执行 qobject_cast 一切都应该没问题
You've inserted your Image class as QObject *, so get it out as QObject * also. Then perform qobject_cast and everything should be fine