2017-05-10 50 views
-1

使用較早的語法,我們不得不使用QtCore.SIGNAL("customContextMenuRequested(QPoint)" thingy。如何將QTableView連接到右鍵單擊菜單

現在隨着Qt5的轉角,舊的QtCore.SIGNAL語法不再酷,因爲它變得絕對。

如何修改下面發佈的工作PyQt4代碼,使其與PyQt5兼容(只關心連接右鍵菜單)?

class TableView(QtGui.QTableView): 
    def __init__(self, parent): 
     QtGui.QTableView.__init__(self, parent) 
     self.rcMenu=QtGui.QMenu(self) 
     self.rcMenu.addAction('My Action') 
     self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) 
     self.connect(self, QtCore.SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) 

def onRightClick(self, QPos=None):  
    parent=self.sender() 
    pPos=parent.mapToGlobal(QtCore.QPoint(5, 20)) 
    mPos=pPos+QPos 

    self.rcMenu.move(mPos) 
    self.rcMenu.show() 

回答

-1

替換:

self.connect(self, QtCore.SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)

有:

self.customContextMenuRequested.connect(self.onRightClick)

class TableView(QtGui.QTableView): 
    def __init__(self, parent): 
     QtGui.QTableView.__init__(self, parent) 
     self.rcMenu=QtGui.QMenu(self) 
     self.rcMenu.addAction('My Action') 
     self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) 
     self.customContextMenuRequested.connect(self.onRightClick) 

def onRightClick(self, QPos=None):  
    parent=self.sender() 
    pPos=parent.mapToGlobal(QtCore.QPoint(5, 20)) 
    mPos=pPos+QPos 

    self.rcMenu.move(mPos) 
    self.rcMenu.show()