QTreeWidget中添加右键菜单

如图所示,在QTreeWidget中添加右键菜单,并设置菜单的槽函数

QTreeWidget中添加右键菜单_第1张图片

使用QMenu和QAction构建菜单

    QMenu *popMenu;
    QAction *delete_node;
    QAction *add_parent_node;
    QAction *add_child_node;

    ui->treeWidget_EditFlow->setContextMenuPolicy(Qt::CustomContextMenu);//右键 不可少否则右键无反应
    connect(ui->treeWidget_EditFlow,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(slots_showrightMenu(QPoint)));

    popMenu = new QMenu(this);
    add_parent_node = new QAction(QStringLiteral("添加测试项目"),this);
    add_parent_node->setStatusTip(QStringLiteral("添加测试项目"));
    add_child_node = new QAction(QStringLiteral("添加指令"),this);
    add_child_node->setStatusTip(QStringLiteral("添加指令"));
    delete_node = new QAction(QStringLiteral("删除项目"),this);
    delete_node->setStatusTip(QStringLiteral("删除项目"));

    connect(add_parent_node,SIGNAL(triggered()),this,SLOT(slots_add_parent_node_Item()));
    connect(add_child_node,SIGNAL(triggered()),this,SLOT(slots_add_child_node_Item()));
    connect(delete_node,SIGNAL(triggered()),this,SLOT(slots_delete_node_Item()));

使用setContextMenuPolicy设置控件在右键时发送customContextMenuRequested信号,设置信号的槽函数slots_showrightMenu。

然后构建菜单,设置菜单项的槽函数。

QTreeWidget中添加右键菜单_第2张图片

/**
 * @brief EditCmdWindow::slots_showrightMenu    在列表上右键显示菜单
 * @param point
 */
void EditCmdWindow::slots_showrightMenu(QPoint point)
{
    popMenu->clear();//清除原有菜单
    popMenu->addAction(add_parent_node);
    popMenu->addAction(add_child_node);
    popMenu->addAction(delete_node);
    //QTreeWidgetItem *item = tree->itemAt(point); //可得到右键条目
    popMenu->exec(QCursor::pos());
}

在槽函数中调用popMenu->exec在当前鼠标位置显示右键菜单

你可能感兴趣的:(QT)