记录qt拖动树节点
1.设置Qtreeview的属性 dragEnabled =true, dragdropmode =dragonly ,defaultdropaction = copyaction
2.设置接收qtreeview节点的控件setacceptdrops =true (各种控件可能不一样)
3.重写接收节点的控件的dragEnterEvent,dragLeaveEvent ,dragMoveEvent ,dropEvent
注意:mimedata的format类型是"application/x-qabstractitemmodeldatalist",这个类型可以通过QStandardItemModel的mimeTypes获得
void dragEnterEvent( QGraphicsSceneDragDropEvent *pEvent )
{
QGraphicsItem::dragEnterEvent(pEvent);
if(pEvent->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))
{
qDebug("%s
",__FUNCTION__);
pEvent->acceptProposedAction();
}
}
void CGraphicsItemRectScreen::dropEvent( QGraphicsSceneDragDropEvent *pEvent )
{
QGraphicsItem::dragEnterEvent(pEvent);
QByteArray arr =pEvent->mimeData()->data("application/x-qabstractitemmodeldatalist");
QVector<int> rows, columns;//节点在QStandardItemModel中的行和列
QVector<QMap<int, QVariant> > data;//节点的基它的属性
QByteArray encoded;
QDataStream stream(&arr, QIODevice::ReadOnly);
int top = INT_MAX;
int left = INT_MAX;
int bottom = 0;
int right = 0;
while (!stream.atEnd()) {
int r, c;
QMap<int, QVariant> v;
stream >> r >> c >> v;
rows.append(r);
columns.append(c);
data.append(v);
top = qMin(r, top);
left = qMin(c, left);
bottom = qMax(r, bottom);
right = qMax(c, right);
}
emit sigDropEvent(this,rows.at(0),columns.at(0),data.at(0)[0].toString());
}
解释节点的mimedata可以看 qabstractitemmodel.cpp里边的方法decodeData,encodeData