Using QAction::setData , in order to pass my own defined object , can not get the object



  • In my project , we must pass our own defined object when menu clicked.

    this is demo code:
    @
    #include "customdefinedemo.h"
    #include "qnewitem.h"

    Q_DECLARE_METATYPE(QNewItem)

    customDefineDemo::customDefineDemo(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
    {
    ui.setupUi(this);
    connect(ui.pushButton , SIGNAL(clicked()),this,SLOT(onBtnClick()));
    }

    customDefineDemo::~customDefineDemo()
    {

    }

    void customDefineDemo::onBtnClick()
    {
    QMenu* pMenu = new QMenu();
    QNewItem* pNewItem = new QNewItem();
    qint16 nAge = 34;
    QVariant qv;
    do
    {
    QAction* pPortraitView = new QAction(tr("New"), this);
    QAction* pAddGroup = new QAction(tr("Open"), this);
    QAction* pDeleteGroup = new QAction(tr("Save"), this);

    pNewItem->setUserInfo(tr("Eric"),nAge);

    pPortraitView->setData( QVariant::fromValue((QObject*)pNewItem) ) ;

    connect(pPortraitView,SIGNAL(triggered()),this,SLOT(triggeredMenuSendMsgContact()));

    pMenu->addAction(pPortraitView);
    pMenu->addAction(pAddGroup);
    pMenu->addAction(pDeleteGroup);
    pMenu->exec(QCursor::pos());
    } while (false);
    delete pMenu;
    }

    void customDefineDemo::triggeredMenuSendMsgContact()
    {
    QAction* pSendMsg= NULL;
    QNewItem* pObj = NULL;
    do
    {
    pSendMsg=qobject_cast<QAction*>(sender());

    *pObj = pSendMsg->data().value<QNewItem>();
    } while (false);
    }
    @

    QNewItem class is own defined , I wanna pass it when menu clicked,but I can not get it ! Where is error? thanx



  • Please use the code tags for a better visibility....
    Also is this really related with QML ?



  • Either <code>QNewItem</code> inherits <code>QObject</code> in which case <code>Q_DECLARE_METATYPE(QNewItem)</code> is wrong, because the type is non-copyable or <code>QNewItem</code> does not inherit <code>QObject</code> in which case the cast to <code>QObject*</code> is wrong (do not use C-style casts in C++).

    Generally you set a <code>QVariant</code> containing a <code>QObject*</code>, expect to get a <code>QVariant</code> containing a <code>QNewItem</code> and try to copy-construct it in a <code>nullptr QNewItem</code> object; this isn't going to happen.

    @
    class QNewItem : public QObject { ... };

    Q_DECLARE_METATYPE(QNewItem*)

    pPortraitView->setData(QVariant::fromValue(pNewItem));

    pObj = pSendMsg->data().value<QNewItem*>();
    delete pObj;
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.