pyqt5-列表右键菜单

from PyQt5.QtWidgets import QApplication, QMainWindow, QListWidget, QAction, QMenu, QVBoxLayout, QWidget
from PyQt5.QtCore import Qt
import sys

from functions import (
    delete_list_item
)


class Example(QMainWindow):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        self.list_widget = QListWidget()
        self.list_widget.addItems(["Item 1", "Item 2", "Item 3", "Item 4"])
        self.list_widget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.list_widget.customContextMenuRequested.connect(self.show_context_menu)
        self.setCentralWidget(self.list_widget)

    def show_context_menu(self, pos):
        item = self.list_widget.itemAt(pos)
        if item:
            menu = QMenu()
            delete_action = QAction("Delete", self)
            delete_action.triggered.connect(lambda: delete_list_item(self.list_widget, item))
            menu.addActions([delete_action])
            menu.exec_(self.list_widget.mapToGlobal(pos))

    def show_context_menu2(self, list_widget: QListWidget, pos):
        item = list_widget.itemAt(pos)
        if item:
            menu = QMenu()
            delete_action = QAction("Delete", self)
            delete_action.triggered.connect(lambda: delete_list_item(self.list_widget, item))
            menu.addActions([delete_action])
            menu.exec_(self.list_widget.mapToGlobal(pos))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Example()
    window.show()
    sys.exit(app.exec_())

你可能感兴趣的:(PyQt5,python)