Qt treewidget右键添加菜单,删除节点

本文介绍如何在Qt应用程序中使用QTreeWidget组件并为其添加右键菜单功能。通过实现信号与槽的连接,自定义上下文菜单策略,并创建QAction和QMenu来响应用户的右键点击事件。

1、添加connect连接,实现信号与槽函数的连接,具体如下:

ui.treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);   //使得该控件可以支持右键菜单

connect(ui.treeWidget, SIGNAL(customContextMenuRequested(const QPoint &)),
		this, SLOT(SlotCustomContextMenuRequested(const QPoint&)));//实现右击添加菜单的信号与槽的连接

2、实现槽函数--SlotCustomContextMenuRequested(const QPoint&),具体如下:

void Test_9::SlotCustomContextMenuRequested(const QPoint& pos)
{
	m_pact = new QAction(QStringLiteral("删除"), this);
	//QAction *pDelAction_1 = new QAction(QStringLiteral("重命名"), this);
	QMenu *popMenu = new QMenu(this);//定义右键弹出菜单
	popMenu->addAction(m_pact);//往菜单内添加QAction 
	// QAction *deleAction = cmenu->addAction("Delete");//另一种创建方式
	connect(m_pact, SIGNAL(triggered()), this, SLOT(DeleteItemFunction()));
	popMenu->exec(QCursor::pos());//弹出右键菜单,菜单位置为光标位置
}

3、实现单击删除节点槽函数--DeleteItemFunction(),具体如下:


                
### 实现 Qt TreeWidget 右键菜单添加节点功能 为了实现在 `QTreeWidget` 中通过右键菜单添加节点的功能,可以按照以下方法进行操作: #### 构建带有自定义上下文菜单QTreeWidget 创建一个继承于 `QTreeWidget` 的类并重写其 `contextMenuEvent` 方法,在该事件处理函数内构建和显示一个简单的弹出式菜单。当用户点击菜单项时触发相应的槽函数用于执行具体逻辑。 ```cpp #include <QTreeWidget> #include <QContextMenuEvent> #include <QAction> class CustomTreeWidget : public QTreeWidget { Q_OBJECT public: explicit CustomTreeWidget(QWidget *parent = nullptr); protected: void contextMenuEvent(QContextMenuEvent *event) override; private slots: void addNode(); }; ``` 在构造器中初始化动作对象,并将其连接到对应的槽上;而在覆写的 `contextMenuEvent()` 函数里,则负责实际展示这个菜单给用户[^1]。 ```cpp CustomTreeWidget::CustomTreeWidget(QWidget *parent) : QTreeWidget(parent), addAction(new QAction(tr("Add Node"), this)) { connect(addAction, SIGNAL(triggered()), SLOT(addNode())); } void CustomTreeWidget::contextMenuEvent(QContextMenuEvent *event) { Q_UNUSED(event); QMenu menu(this); menu.addAction(addAction); menu.exec(mapToGlobal(event->pos())); // 显示菜单位置由鼠标指针决定 } ``` 最后就是实现具体的 `addNode()` 槽函数用来真正完成新增加节点的任务了。这里可以根据需求选择是在当前选中的项目下作为子项还是作为一个新的顶层条目加入树结构之中[^2]。 ```cpp void CustomTreeWidget::addNode() { QTreeWidgetItem* selectedItem = currentItem(); // 获取当前被选中的项 QString text = tr("New Item"); if (selectedItem != nullptr && !isTopLevel()) { // 如果有选定项则作为它的孩子插入 new QTreeWidgetItem(selectedItem, QStringList(text)); } else { // 否则就当作根级别的元素添加进去 new QTreeWidgetItem(this, QStringList(text)); } } ``` 上述代码片段展示了如何基于 `QTreeWidget` 类扩展出自定义行为——即支持通过右击调用快捷方式来动态地往视图里面追加数据记录的方法。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值