如何创建上下文菜单以删除 qtableview 内部的行 python

How to create contextmenu to delete row for inside of qtableview python

下面是我使用的代码: 如何创建上下文菜单以删除 qtableview 内部的行 python.

它正在显示菜单,即使我也单击了 Qpushbutton,但我只需要在 qtableview 内部显示删除菜单。并让我知道删除 qtableview 数据行的方法。 请告诉我解决方案。

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import uic
import sys
import sqlite3


class UI(QMainWindow):
    def __init__(self):
        super(UI, self).__init__()
        uic.loadUi("tableview.ui", self)
        self.show()

        self.view_msa()

        self.pushButton.clicked.connect(self.view_msa)

                
    def view_msa(self):
        self.model = QtGui.QStandardItemModel(self)
        self.tableView.setModel(self.model)

        conn = sqlite3.connect('book.db')
        cur = conn.cursor()
        cur.execute("SELECT * FROM card")
        db_data = cur.fetchall()
        print(db_data)
        for line in db_data:
            row = []
            for item in line:
                cell = QStandardItem(str(item))
                row.append(cell)

            self.model.setHorizontalHeaderLabels(["Name","Age","Gender"])
            self.model.appendRow(row)

    def contextMenuEvent(self, event):
        self.click_menu = QtWidgets.QMenu()
        renameAction = QtWidgets.QAction('Delete', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.click_menu.addAction(renameAction)

        self.click_menu.popup(QtGui.QCursor.pos())

    def renameSlot(self, event):
        print("Renameing slot called")

app = QApplication(sys.argv)
window = UI()
app.exec_()

所有小部件都有 contextMenuPolicy property, which if set to QtCore.Qt.CustomContextMenu allows to connect to the customContextMenuRequested(pos) signal (note that the pos is in widget coordinates). From there you can access the index that is at the mouse position through indexAt,或者更好的是,获取 selectedIndexes(如果启用了多选,这很有用)。

class UI(QMainWindow):
    def __init__(self):
        super(UI, self).__init__()
        # ...

        self.tableView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.tableView.customContextMenuRequested.connect(self.tableMenu)

    def tableMenu(self, pos):
        selected = self.tableView.selectedIndexes()
        if not selected:
            return
        menu = QtWidgets.QMenu()
        deleteAction = menu.addAction('Delete rows')
        deleteAction.triggered.connect(lambda: self.removeRows(selected))
        menu.exec_(QtGui.QCursor.pos())

    def removeRows(self, indexes):
        # get unique row numbers
        rows = set(index.row() for index in indexes)
        # remove rows in *REVERSE* order!
        for row in sorted(rows, reverse=True):
            self.model.removeRow(row)

请注意,在这种情况下,您必须使用 menu.exec()(这通常是首选方法),而不是 popup(),否则该功能将立即 return,并且菜单不会' t 可能因为鼠标事件的内部处理而出现:exec 阻塞直到它 returns(无论它的任何动作被触发还是关闭),popup return马上。