pyqt5的QListWidget中设置右键菜单

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

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

Qt.ContextMenuPolicy 是一个枚举类型:

ConstantValueDescription
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 来创建右键菜单.

listWidget.setContextMenuPolicy(3) 设置菜单
listWidget.customContextMenuRequested[QtCore.QPoint].connect() 绑定方法 

通过上面的Qpoint 获取列表中的 选定的选项 item :

item = listWidget.itemAt(x,y) 

根据point的坐标移除 列表选项中的item :

listwidget.removeItemWidget(listwidget.takeItem(listwidget.row(item)))

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/liugp/p/10471846.html