以下代码,已经验证OK了。
但有个问题,QVariant(Qt::transparent).toByteArray()的传送出去,是为了什么?(说明一下,这是项目中的,看了下,它仅仅是作为判定数据合法性)
- C/C++ code
#define DATA_ID1 "Text/stringids"#define DATA_ID2 "Text/colordata"//发送方void MyWidget1::mousePressEvent(QMouseEvent *pMouseEvent){ qDebug ("%d: %s: %s enter", __LINE__, __FILE__, __FUNCTION__); QWidget::mousePressEvent(pMouseEvent); QDrag* pDrag = new QDrag(this); //Qt自动释放 QMimeData* pMimeData = new QMimeData(); //Qt自动释放 if ((NULL!=pDrag) && (NULL!=pMimeData)) { //set the mime data QString strData = "this is a test for drag and drop"; pMimeData->setData(DATA_ID1, strData.toAscii()); pMimeData->setData(DATA_ID2, QVariant(Qt::transparent).toByteArray()); pDrag->setMimeData(pMimeData); pDrag->exec(Qt::CopyAction | Qt::MoveAction); }}//接收方MyWidget2::MyWidget2(QWidget *parent) : QWidget(parent){ setAcceptDrops(true);}void MyWidget2::dragEnterEvent(QDragEnterEvent *pDragEnterEvent){ qDebug ("%d: %s: %s enter", __LINE__, __FILE__, __FUNCTION__); QString strData(pDragEnterEvent->mimeData()->data(DATA_ID1)); QVariant varColor(pDragEnterEvent->mimeData()->data(DATA_ID2)); QColor color = varColor.value<QColor> (); if (color.isValid()) { pDragEnterEvent->acceptProposedAction(); pDragEnterEvent->accept(); this->setMouseTracking(true); }}void MyWidget2::dropEvent(QDropEvent *pDropEvent){ qDebug ("%d: %s: %s enter", __LINE__, __FILE__, __FUNCTION__); //get the mime data QString strData(pDropEvent->mimeData()->data(DATA_ID1)); QVariant varColor(pDropEvent->mimeData()->data(DATA_ID2)); QColor color = varColor.value<QColor>(); if (color.isValid()) { //todo: }}
------解决方案--------------------
因为pMimeData setdata的时候 指明了数据类型 DATA_ID2,所以要把QVariant 的转换为ByteArray