转自:https://blog.csdn.net/huapenguag/article/details/50669701
1 在目标View上设置右键策略
//! 支持右键菜单
m_treeView->setContextMenuPolicy(Qt::CustomContextMenu);
<!---其中 m_treeView是一个QtreeView
2 建立信号槽的连接
//! 右键菜单信号槽
connect(m_treeView, SIGNAL(customContextMenuRequested(const QPoint& )), this, SLOT(ShowContextMenu(const QPoint&)));
3 实现槽
void ShowContextMenu(const QPoint& pos)
{
//! 创建右键菜单
QMenu menu;
//! 添加右键菜单中的action
//! 例如添加 action1
QAction* action1 = new QAction(&menu);
action1 ->setObjectName("action1 ");
action1 ->setText(tr("1111"));
menu.addAction(action1 );
//! 显示该菜单,进入消息循环
menu.exec(m_treeView->mapToGlobal(pos)/*全局位置*/);
}
本文详细介绍了如何在Qt中为QTreeView控件设置右键菜单,包括设置右键策略、建立信号槽连接以及实现显示菜单的槽函数。通过具体代码展示了如何创建菜单、添加菜单项并显示菜单。
4019

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



