简体   繁体   中英

Store QPointer into a QVariant

Can I store a QPointer , for example a QPointer<QTcpSocket> inside a QVariant and later extract it from it?

I tried with:

    QObject *ob = new QObject();
    QPointer<QObject> qp(ob);
    QVariant qv(qp);

But I got an error - QVariant::QVariant(void*)' is private .

After some more research, it is possible by using QVariant::fromValue() and QVariant::value() .

Example code:

    QTcpSocket *ob = new QTcpSocket();
    qDebug("%p", ob);
    QPointer<QTcpSocket> qp(ob);
    QVariant qv = QVariant::fromValue(qp);
    qp = qv.value<QPointer<QTcpSocket> >();
    qDebug("%p", qp.data());
    delete ob;
    qDebug("%p", qp.data());

This gives:

0x137c070
0x137c070
0x0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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