Qt实现树节点的需求拖拽

Qt实现树节点的需求拖拽
直接进入正题,各位官爷先了解一下需求:
树上节点拖拽操作,调整设备所属的树节点,里面要做一些类型合法性判断,调整树节点时,也只能放在相同类别的设备文件夹下

代码实现:

首先再创建树的地方加入三行代码:

//设置树节点允许拖拽
m_treeWidget->setDragDropMode(QAbstractItemView::DragDrop);
//允许接受drop操作,注意,不写的话无法进入重写的事件
m_treeWidget->setAcceptDrops(true);
//拖拽节点的移动,不写的移动的时候原节点不会删除
m_treeWidget->setDefaultDropAction(Qt::MoveAction);

然后新建一个自定义树类继承QQTreeWidget:
头文件:

#ifndef ZDYTREEWIDGET_H
#define ZDYTREEWIDGET_H
#include 

class ZDYTreeWidget : public QTreeWidget
{
    Q_OBJECT

public:
	explicit ZDYTreeWidget();
	~ZDYTreeWidget();

protected:
	//鼠标压下事件,启动拖拽事件,用来获取拖拽的节点
	void mousePressEvent(QMouseEvent* event) override;
    //drop释放事件
    void dropEvent(QDropEvent* event) override;

private:
	QTreeWidgetItem *m_mousetree;

};
#endif // ZDYTREEWIDGET_H

源文件:

#include "zdytreewidget.h"
#include 
#include 
#include 
#include 
#include 
#include 
#include "dboperate.h"

ZDYTreeWidget::ZDYTreeWidget()
{

}

ZDYTreeWidget::~ZDYTreeWidget()
{
	
}

void ZDYTreeWidget::dropEvent(QDropEvent *event)
{
		//获取放置的父节点
		QTreeWidgetItem *item = itemAt(event->pos());
		if (item == nullptr)
			return;
		
		//根据自己的项目逻辑编写
		QVariant var = item->data(1, Qt::UserRole + 1);
		RWTree *rwtree = var.value();
		QVariant m_mousevar = m_mousetree->data(1, Qt::UserRole + 1);
		RWTree * pressrwtree= m_mousevar.value();
		
		if (rwtree->type == Type_FA_GSJD_SC && pressrwtree->type == Type_FA_GSJD_SC_SB)
		{
			return QTreeWidget::dropEvent(event);
			event->accept();

			return;
		}
		else if (rwtree->type == Type_FA_GSJD_ZXBP && pressrwtree->type == Type_FA_GSJD_ZXBP_SB)
		{
			return QTreeWidget::dropEvent(event);
			event->accept();

			return;
		}
		else if (rwtree->type == Type_FA_GSJD_DXBP && pressrwtree->type == Type_FA_GSJD_DXBP_SB)
		{
			return QTreeWidget::dropEvent(event);
			event->accept();

			return;
		}
		else if (rwtree->type == Type_FA_GSJD_SY && pressrwtree->type == Type_FA_GSJD_SY_SB)
		{
			return QTreeWidget::dropEvent(event);
			event->accept();

			return;
		}
		
		else
		{
			QMessageBox::information(this, "错误", "请在相同类型的设备之间移动");
			event->ignore();
		}

		return;
}

void ZDYTreeWidget::mousePressEvent(QMouseEvent* event)
{
	//获取拖拽的节点
	m_mousetree = static_cast(this->itemAt(event->pos()));

	QTreeWidget::mousePressEvent(event);
}

总结:

那我们来总结一下,基本流程就是:设置树的属性,使其支持拖拽操作等,然后定义一个类继承QTreeWidget重写里面的mousePressEvent和dropEvent两个事件,最后根据我们自己实际需求来设置拖拽条件。所以,今天你学废了码???

你可能感兴趣的:(qt,树结构,c++)