pyqt5的QListWidget中設置右鍵菜單


 QListWidget 是繼承 QWidget 的, 所以 QListWidget 是有右鍵菜單的,

從文檔上可以找到 QWidget 上有以下兩個與右鍵菜單有關的函數:

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 來創建右鍵菜單.

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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM