firemail
标题: Qt 中,如何通过QAction::setData , 传送自定义的数据 Q_DECLARE_METATYPE [打印本页]
作者: Qter 时间: 2020-3-17 17:26
标题: Qt 中,如何通过QAction::setData , 传送自定义的数据 Q_DECLARE_METATYPE
最近,项目中有这样的需求,通过QAction::setData , 传送自定义的数据。在网上查了很多的资料,都是模模糊糊的说几句,都没有说到点子上,更有人给出了完全违背Qt理念的解决方案。下面就是我写的一个例子代码:
1、自定义数据:
在此,以自定义的类为例子,代码如下:
//.h
#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 // QNEWITEM_H
//.cpp
#include "qnewitem.h"
QNewItem:NewItem(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;
}
2、在调用的CPP开头,必须定义这样声明:
#include "qnewitem.h"
Q_DECLARE_METATYPE(QNewItem*)
其他的就没什么好说的了,看代码,你们的都懂的。
#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:nBtnClick()
{
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;
}
}
欢迎光临 firemail (http://firemail.wang:8088/) |
Powered by Discuz! X3 |