转载地址: http://www.cnblogs.com/yogalau/p/3954042.html?utm_source=tuicool

QListWidget 是继承 QWidget 的, 所以 QListWidget 是有右键菜单的,

从文档上可以找到 QWidget 上有以下两个与右键菜单有关的函数:

  • Qt.ContextMenuPolicy contextMenuPolicy (self)
  • setContextMenuPolicy (self, Qt.ContextMenuPolicy policy)

Qt.ContextMenuPolicy 是一个枚举类型:

Constant Value Description
Qt.NoContextMenu 0 the widget does not feature a context menu, context menu handling is deferred to the widget's parent.
Qt.PreventContextMenu 4 the widget does not feature a context menu, and in contrast to NoContextMenu, the handling is not deferred to the widget's parent. This means that all right mouse button events are guaranteed to be delivered to the widget itself through mousePressEvent(), and mouseReleaseEvent().
Qt.DefaultContextMenu 1 the widget's QWidget.contextMenuEvent() handler is called.
Qt.ActionsContextMenu 2 the widget displays its QWidget.actions() as context menu.
Qt.CustomContextMenu 3 the widget emits the QWidget.customContextMenuRequested() signal.

现在主要要说的是利用 Qt.CustomContextMenu 来创建右键菜单.

QWidget 和它的子类 contextMenuPolicy 的默认值是 Qt.DefaultContextMenu 的,

所以我们需要通过 setContextMenuPolicy(QtCore.Qt.CustomContextMenu) 重新来设置他的值

(在Qt设计师中, 可以直接修改 contextMenuPolicy 的值为 CustomContextMenu 并且写入到UI文件中,

所以用Qt设计师可以不用 setContextMenuPolicy 方法来设置)

CustomContextMenu 它所发出的是一个 customContextMenuRequested 信号 (signal) 如下:

  • void customContextMenuRequested (const QPoint&)

这个信号是QWidget唯一与右键菜单有关的信号(也是自有的唯一信号), 同时也是很容易被忽略的信号(signal)

*注: 文档中QWidget方法和属性巨量多, 以致我都看不到底部居然还有"一个"信号

既然有信号, 那么我们就可以轻松自定义我们想要的右键菜单了.

了解到这些之后, 我们就着手编写槽(slot)了.

 def myListWidgetContext(self, point):
popMenu = QtGui.QMenu()
popMenu.addAction(QtGui.QAction(u'添加', self))
popMenu.addAction(QtGui.QAction(u'删除', self))
popMenu.addAction(QtGui.QAction(u'修改', self)) popMenu.exec_(QtGui.QCursor.pos())

接着就是连接槽:

 self.connect(self.UI.BtnOpen, QtCore.SIGNAL('customContextMenuRequested (const QPoint&)'), self.openright)

效果:

最新文章

  1. Python补充06 Python之道
  2. Struts2 入门
  3. [linux系统]--搭建ftp服务器并且 创建用户 设置密码
  4. JS魔法堂:被玩坏的innerHTML、innerText、textContent和value属性
  5. HR外包系统 - 客户公司薪资规则 报表需求 记入系统
  6. Android自动化初探:ADB
  7. bzoj3413
  8. Appium的前世今生
  9. KVO和通知中心
  10. ajax学习之post请求步骤
  11. 使用Pushlet来实现服务器端向客户端推送信息
  12. HTML5 的WebSocket
  13. .NET Core WebApi中实现多态数据绑定
  14. 当Vue中img的src是动态渲染时不显示问题
  15. ubuntu 搜狗输入法 在中断失效
  16. iOS开发ffmpeg SDK 编译和集成
  17. 关于Windows下无法在MySQL安装目录找到配置文件my.ini
  18. 【python】实例-创建文件并通过键盘输入字符
  19. websocket使用
  20. python基础之01数据类型-变量-运算浅解

热门文章

  1. Unity响应Android的返回键,退出当前Activity
  2. 2016年11月3日--Window.document对象
  3. Android的一种MVP模式框架
  4. 34 网络相关函数(二)——live555源码阅读(四)网络
  5. java抓取快递信息
  6. non
  7. FWT
  8. C语言中#define的用法(转)
  9. history/location操作 /navigator 操作/ screen操作
  10. XsltListViewWebPart 和自定义列表视图