2012-02-16 86 views
2

這裏是我的問題的詳細信息:我有這些小部件 - QMenuBar,QTableWidget和QToolbar。這裏是我的代碼示例:QMenu for PySide/PyQt中的QTableWidget

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)。提前致謝。

+0

你說的是對行/列表頭彈出菜單? – 2012-02-16 15:14:24

+0

@AndrejsCainikovs,是的。 – SaulTigh 2012-02-16 20:14:47

回答

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())