如何在PyQt的QTableView的每个单元格中添加右键菜单 [英] how to add a right click menu to each cell of QTableView in PyQt

查看:1760
本文介绍了如何在PyQt的QTableView的每个单元格中添加右键菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在右键单击菜单的QTAbleView的每个单元格中添加一个右键单击菜单以删除,重命名或打开图像,我尝试过发现所有人都试图将菜单添加到tableview的标题中,我在下面尝试过但这似乎在下面的代码中不起作用.

I want to add a right click menu to delete, rename or open image in each of cell of QTAbleView in the rigt click menu, I have tried and found everyone is trying to add menu to a header in tableview, i tried below but that seems not working in the code below..

class GalleryUi(QtGui.QTableView):
    """ Class contains the methods that forms the
        UI of Image galery
    """
    def __init__(self, imagesPathLst=None, parent=None):
        super(GalleryUi, self).__init__(parent)
        self.__sw = QtGui.QDesktopWidget().screenGeometry(self).width()
        self.__sh = QtGui.QDesktopWidget().screenGeometry(self).height()
        self.__animRate = 1200
        self._imagesPathLst = imagesPathLst
        self._thumb_width = 200
        self._thumb_height = self._thumb_width + 20
        self.setUpWindow(initiate=True)

        self._startControlBar()

        self._connections()

    def contextMenuEvent(self, event):

        index = self.indexAt(event.pos())
        menu = QtGui.QMenu()
        renameAction = QtGui.QAction('Exit', self)
        renameAction.triggered.connect(self.close)
        self.menu.addAction(renameAction)
        self.menu.popup(QtGui.QCursor.pos())

    def closeEvent(self,event):
        # in case gallery is launched by Slideshow this is not needed
        if hasattr(self, 'bar'):
            self.bar.close()

    def _startControlBar(self):
        if not self._slideShowWin:
            self.bar = controlBar.ControlBar()
            self.bar.show()
            self.bar.exitBtn.clicked.connect(self.close)
            self.bar.openBtn.clicked.connect(self.selectSetNewPath)


    def _connections(self):
        self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.connect(self, QtCore.SIGNAL(self.customContextMenuRequested(QtCore.QPoint)), self, QtCore.SLOT(displayMenu(QtCore.QPoint)))

    def displayMenu(self, pos):
        self.menu = QtGui.QMenu()
        self.menu.addAction(self.close)
        self.menu.exec_(self.mapToGlobal(event.pos()))

    def selectSetNewPath(self):

        path = utils._browseDir("Select the directory that contains images")
        self._imagesPathLst = utils.ingestData(path)
        # sets model when new folder is choosen
        self.updateModel()

    def setUpWindow(self, initiate=False):
        """ Method to setup window frameless and fullscreen,
            setting up thumbnaul size and animation rate
        """

        if not self._imagesPathLst:
            self.selectSetNewPath()
        # sets model once at startup when window is being drawn!
        if initiate:
            self.updateModel()
        self.setGeometry(0, 0, self.__sw, self.__sh)
        self.setColumnWidth(self._thumb_width, self._thumb_height)
        self.setShowGrid(False)
        self.setWordWrap(True)
        self.show()

        self.resizeColumnsToContents()
        self.resizeRowsToContents()
        self.selectionModel().selectionChanged.connect(self.selChanged)

    def updateModel(self):
        col = self.__sw/self._thumb_width 
        self._twoDLst = utils.convertToTwoDList(self._imagesPathLst, col)
        lm = MyListModel(self._twoDLst, col,
            (self._thumb_width, self._thumb_height), self)
        self.setModel(lm)



    def keyPressEvent(self, keyevent):
        """ Capture key to exit, next image, previous image,
            on Escape , Key Right and key left respectively.
        """
        event = keyevent.key()
        if event == QtCore.Qt.Key_Escape:
            self._exitGallery()



def main(imgLst=None):
    """ method to start gallery standalone
    """
    app = QtGui.QApplication(sys.argv)
    window =  GalleryUi(imgLst)
    window.raise_()
    sys.exit(app.exec_())

if __name__ == '__main__':
    current_path = os.getcwd()
    if len(sys.argv) > 1:
        current_path = sys.argv[1:]
    main(utils.ingestData(current_path))

推荐答案

QTableView具有contextMenuEvent()事件,以显示右键菜单:

QTableView has contextMenuEvent() event, to show a right-click menu:

  • 在此事件中创建一个QMenu
  • QMenu
  • 中添加一些QAction
  • 使用QAction
  • triggered信号将每个QAction连接到插槽
  • QMenu上呼叫popup(QCursor.pos())
  • Create a QMenu inside this event
  • Add some QActions to QMenu
  • connect each QAction to slots using triggered signal of QAction
  • call popup(QCursor.pos()) on QMenu

当用户右键单击tableView时,将选择鼠标指针下方的单元格,同时将显示一个菜单.当用户在菜单上选择一个动作时,将调用所连接的插槽,在该插槽中获取所选表格的单元格,然后对该单元格执行所需的操作.

When user right-click the tableView the cell under the mouse pointer will be selected and at the same time a menu will appear. When user selects an action on the menu, the connected slot will be called, get the selected cell of tabel in this slot and perform the required action on this cell.

...
def contextMenuEvent(self, event):
    self.menu = QtGui.QMenu(self)
    renameAction = QtGui.QAction('Rename', self)
    renameAction.triggered.connect(lambda: self.renameSlot(event))
    self.menu.addAction(renameAction)
    # add other required actions
    self.menu.popup(QtGui.QCursor.pos())
    ...

def renameSlot(self, event):
    print "renaming slot called"
    # get the selected row and column
    row = self.tableWidget.rowAt(event.pos().y())
    col = self.tableWidget.columnAt(event.pos().x())
    # get the selected cell
    cell = self.tableWidget.item(row, col)
    # get the text inside selected cell (if any)
    cellText = cell.text()
    # get the widget inside selected cell (if any)
    widget = self.tableWidget.cellWidget(row, col)
...

这篇关于如何在PyQt的QTableView的每个单元格中添加右键菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆