加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Qt创建鼠标右键菜单

(2015-01-03 11:53:28)
标签:

股票

分类: Qt学习
第一步:

QWidget及其子类都可有右键菜单,首先设置QWidget与右键菜单有关的函数setContextMenuPolicy()。

如设置QTreeView的相关函数为:this->ui.treeView->setContextMenuPolicy(Qt::CustomContextMenu);

Qt::ContextMenuPolicy枚举类型包括:Qt::DefaultContextMenu, Qt::NoContextMenu, Qt::PreventContextMenu, Qt::ActionsContextMenu, and Qt::CustomContextMenu,其中如果设置该类型为Qt::CustomContextMenu,则点击鼠标右键会发射信号customContextMenuRequested(const QPoint)。

第二步:

在头文件中声明右键关联的槽函数ShowMouseRightButton(const QPoint); 并且设置信号customContextMenuRequested(const QPoint)与该槽函数的关联,例如:connect(ui.treeView, SIGNAL(customContextMenuRequested(const QPoint)), this, SLOT(ShowMouseRightButton(const QPoint)));

第三步:

实现对应的右键关联的槽函数,如ShowMouseRightButton(const QPoint);

void ShowMouseRightButton(const QPoint& pos)
{
       QMenu *qMenu = NULL;

       if (qMenu)
       {
               delete qMenu;
               qMenu = NULL;
       }

       qMenu = new QMenu(ui.treeView);

       QAction* closePaneAction = new QAction("&Close",this);
       connect(closePaneAction, SIGNAL(triggered()), this, SLOT(close()));

       QAction* addTreeItemAction = new QAction("&AddItem", this);
       connect(addTreeItemAction, SIGNAL(triggered()), this, SLOT(AddTreeItem()));

       qMenu->addAction(closePaneAction);
       qMenu->addAction(addTreeItemAction);

       qMenu->exec(QCursor::pos()); //在鼠标点击的位置显示鼠标右键菜单

}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有