2017-05-30 70 views

回答

2

你只需重写照顾它的方法。

在这种情况下,您将覆盖mousePressEvent,看看这个,看看它是否有意义,并为你需要的工作。

import sys 
from PyQt5.QtCore import Qt 
from PyQt5.QtWidgets import QApplication 
from PyQt5.QtWidgets import QWidget 


class MyWidget(QWidget): 


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

    def mousePressEvent(self, QMouseEvent): 
     if QMouseEvent.button() == Qt.LeftButton: 
      print("Left Button Clicked") 
     elif QMouseEvent.button() == Qt.RightButton: 
      #do what you want here 
      print("Right Button Clicked") 

if __name__ == "__main__": 

    app = QApplication(sys.argv) 
    mw = MyWidget() 
    mw.show() 
    sys.exit(app.exec_()) 

另一个好方法是在对象中安装一个事件过滤器并覆盖它的eventFilter。在那个方法里面,你会做出你想要的。请记住,您始终可以使用pyqtSignal获得良好的实践,并调用另一个对象来完成这项工作,而不是用很多逻辑来重载该方法。

这里是另外一个小例子:

import sys 

from PyQt5.QtCore import QEvent 
from PyQt5.QtCore import Qt 
from PyQt5.QtWidgets import QApplication 
from PyQt5.QtWidgets import QWidget 

class MyWidget(QWidget): 

    def __init__(self): 
     super(MyWidget, self).__init__() 
     self.installEventFilter(self) 

    def eventFilter(self, QObject, event): 
     if event.type() == QEvent.MouseButtonPress: 
      if event.button() == Qt.RightButton: 
       print("Right button clicked") 
     return False 

if __name__ == "__main__": 

    app = QApplication(sys.argv) 
    mw = MyWidget() 
    mw.show() 
    sys.exit(app.exec_()) 

注:请记住,这最后一个例子将接收事件的所有种类,所以你必须要小心,并确保它是一个你想要的,而不是运行时中断您的应用程序调用不存在的事件的方法,因为它不是那种类型。例如,如果您在未确认之前致电event.button(),那么它将是QEvent.MouseButtonPress。您的应用程序当然会中断。

还有其他方法可以做到这一点,这些是最知名的。

0

我想出了一个很简单的方法来完成这个工作,并且完美地工作。在ControlMainWindow类中添加以下初始化上下文菜单政策CustomeContextMenu其中listWidget_extractedmeters将是你QListWidget名称:

self.listWidget_extractedmeters.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) 
self.listWidget_extractedmeters.connect(self.listWidget_extractedmeters,QtCore.SIGNAL("customContextMenuRequested(QPoint)"), self.listItemRightClicked) 

然后在ControlMainwindow类以下功能允许您添加上下文菜单项,并呼吁一个函数执行一些功能:

def listItemRightClicked(self, QPos): 
    self.listMenu= QtGui.QMenu() 
    menu_item = self.listMenu.addAction("Remove Item") 
    self.connect(menu_item, QtCore.SIGNAL("triggered()"), self.menuItemClicked) 
    parentPosition = self.listWidget_extractedmeters.mapToGlobal(QtCore.QPoint(0, 0))   
    self.listMenu.move(parentPosition + QPos) 
    self.listMenu.show() 

def menuItemClicked(self): 
    currentItemName=str(self.listWidget_extractedmeters.currentItem().text()) 
    print(currentItemName) 
+0

如何在PyQT5中做到这一点? – Imran