QMenu for PySide / PyQt中的QTableWidget

时间:2012-02-16 15:05:54

标签: python qt contextmenu pyside qtablewidget

这是我的问题细节:我有这些小部件 - QMenuBar,QTableWidget和QToolbar。这是我的代码示例:

import sys
from PySide import QtGui
class Example(QtGui.QMainWindow):

  def __init__(self):
      super(Example, self).__init__()

      self.header_lbls = ['Name', 'Second Name', 'Surname', 'Birth Date', 'Phone Number', 'Skype', 'E-mail']

      self.table = QtGui.QTableWidget(10, 7)
      self.table.setHorizontalHeaderLabels(self.header_lbls)
      self.setCentralWidget(self.table)

      #ACTIONS
      self.createActions()

      #MENUBAR
      self.createMenus()

      #TOOLBAR
      self.createToolbar()

      #STATUSBAR
      self.creatStatusbar()

def contextMenuEvent(self, event):
     self.menu = QtGui.QMenu(self.table)
     self.menu.addAction(self.aboutAct)
     self.menu.exec_(QtGui.QCursor.pos())

def createActions(self):
     self.exitAct = QtGui.QAction('E&xit', self, shortcut='Ctrl+Q',
        statusTip='Exit the application', triggered=app.exit)

def createMenus(self):
    self.menubar = self.menuBar()
    self.fileMenu = self.menuBar().addMenu("&File")
    self.fileMenu.addAction(self.exitAct)

def createToolbar(self):
    self.toolbar = self.addToolBar('Toolbar')
    self.toolbar.addAction(self.settingsAct)
    self.toolbar.addSeparator()
    self.toolbar.addAction(self.exitAct)

def creatStatusbar(self):
    self.statusBar()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = Example()
    window.setGeometry(80, 80, 800, 600)
    window.show()
    sys.exit(app.exec_())

问题是:例如,如何使QMenu在Microsoft Excel中使用(我的意思是只添加/删除行/ coloumns)。提前谢谢。

1 个答案:

答案 0 :(得分:7)

使用表格标题视图的customContextMenuRequested信号:

class Example(QtGui.QMainWindow):
    def __init__(self):
        ...

        header = self.table.horizontalHeader()
        header.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        header.customContextMenuRequested.connect(self.handleHeaderMenu)

    def handleHeaderMenu(self, pos):
        print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos))
        menu = QtGui.QMenu()
        menu.addAction('Add')
        menu.addAction('Delete')
        menu.exec_(QtGui.QCursor.pos())