首页 文章

PyQt - 右键单击一个小部件

提问于
浏览
1

我正在使用PyQt,我想向窗口小部件添加右键单击,但我无法在线找到关于此主题的任何代码 .

你怎么能这样做 ?

2 回答

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

    Note: 请记住,最后一个示例将收到所有类型的事件,因此您必须小心并确保它存在,因为它不是那种情况 . 例如,如果你在没有确定之前调用 event.button() 它是 QEvent.MouseButtonPress 你的应用程序会破坏当然 .

    还有其他方法,这些是最知名的方法 .

  • -2

    我想出了一个非常简单的方法来做到这一点并且完美地工作 . 在ControlMainWindow类中添加以下内容以将Context菜单策略初始化为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)
    

相关问题