Recently, in a project, there was a need to transmit custom data using QAction::setData. I’ve searched online for a lot of information, but it’s all a bit vague, and none of them hit the mark. Some even provide solutions that completely contradict Qt’s principles. Below is an example code I wrote:
Custom data: Here, taking a custom class as an example, the code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #ifndef QNEWITEM_H #define QNEWITEM_H #include <QObject> class QNewItem : public QObject { public: QNewItem(QObject *parent = 0 ); ~QNewItem(); bool setUserInfo(QString& strName,qint16& nAge); private: QString m_strName; qint16 m_nAge; }; #endif
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 #include "qnewitem.h" QNewItem::QNewItem(QObject *parent) : QObject(parent) { } QNewItem::~QNewItem() { } bool QNewItem::setUserInfo( QString& strName,qint16& nAge ){ bool bRet = false ; do { if ( strName.isEmpty() || nAge >200 && nAge<0 ) break ; m_strName = strName; m_nAge = nAge; bRet = true ; } while (false ); return bRet; }
At the beginning of the calling CPP file, you must declare it like this:
1 2 3 #include "qnewitem.h" Q_DECLARE_METATYPE(QNewItem*)
There’s not much else to say; when you look at the code, you’ll understand everything.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 #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(pNewItem) ) ; connect(pPortraitView,SIGNAL(triggered()),this,SLOT(triggeredMenuSendMsgContact())); pMenu->addAction(pPortraitView); pMenu->addAction(pAddGroup); pMenu->addAction(pDeleteGroup); pMenu->exec(QCursor::pos()); } while (false ); if ( pMenu != nullptr ) { delete pMenu; pMenu = nullptr; } } void customDefineDemo::triggeredMenuSendMsgContact() { QAction* pSendMsg= NULL; QNewItem* pObj = NULL; do { pSendMsg=qobject_cast<QAction*>(sender()); pObj = pSendMsg->data().value<QNewItem*>(); } while (false ); if ( pObj != nullptr ) { delete pObj; pObj = nullptr; } }