Pyqt在QListWidget中添加右键菜单

Pyqt 的资料奇少, 攻破难点之后, 就在这里记一下笔记.

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

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

Qt.ContextMenuPolicy 是一个枚举类型:

ConstantValueDescription
Qt.NoContextMenu0the widget does not feature a context menu, context menu handling is deferred to the widget's parent.
Qt.PreventContextMenu4the 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.DefaultContextMenu1the widget's QWidget.contextMenuEvent() handler is called.
Qt.ActionsContextMenu2the widget displays its QWidget.actions() as context menu.
Qt.CustomContextMenu3the 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) 如下:

这个信号是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.myListWidget.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)

文档在手, 天下我有啊~

 

转载于:https://www.cnblogs.com/yogalau/p/3954042.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值