QVariant 存放指针

QVariant v = 
QVariant::fromValue

((void *) yourPointerHere);

yourPointer = (YourClass *) v.value<void *>();





You can store many types of data into QVariant, like int, string, etc. Also you can store pointers, but only pointers to void (void ). But what happens when you want to set a property of a object to a instance of class, with setProperty, and after that, you want to retrieve that property? QVariant accepts void , so you can do something like the following, to store it into QVariant:

QVariant v = QVariat::FromValue((void *) yourPointerHere);

and then something like this, in order to retrieve it back from QVariant://你也可以恢复到指针

yourPointer = (YourClass *) v.value<void *>();

Having this done each time you have to get the property or set the property is a bit tendentious. We can make this more friendly, using templates:

template <class T> class VPtr
{
public:
    static T* asPtr(QVariant v)
    {
    return  (T *) v.value<void *>();
    }
    static QVariant asQVariant(T* ptr)
    {
    return QVariant::FromValue((void *) ptr);
    }
};

So how do you use this? Assuming you have a class MyClass, and you want to store a pointer to this class as a property of a QWidget, or any QObject, or you want to convert it to QVariant, you can do the following:

MyClass *p;
QVariant v = VPtr<MyClass>::asQVariant(p);
MyClass *p1 = VPtr<MyClass>::asPtr(v);

I think this is more developer friendly than having to write each time those conversion code sequences.

转载:http://ju.outofmemory.cn/entry/179497
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值