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应用程序中使用QTreeWidget组件并为其添加右键菜单功能。通过实现信号与槽的连接,自定义上下文菜单策略,并创建QAction和QMenu来响应用户的右键点击事件。
3998

被折叠的 条评论
为什么被折叠?



