代码之家  ›  专栏  ›  技术社区  ›  speedyTeh

PyQT:禁用鼠标左键单击

  •  0
  • speedyTeh  · 技术社区  · 13 年前

    有没有办法禁用(和覆盖)Qt中的鼠标左键点击?更好的是,在PyQt中。我在小部件类中写了这样的东西:

    def mousePressEvent(self,event): 
        if event.button() == QtCore.Qt.RightButton:
            print "left"
    

    还尝试了以下内容:

        def eventFilter(self, source, event):
    
            if event.type()==QtCore.QEvent.MouseButtonPress:
                if event.button() == QtCore.Qt.LeftButton:
                    print "left"
    
    ...
    app.installEventFilter(ui)
    

    但只有当我在左键单击没有任何作用的地方单击时,例如在表单背景上,才会执行此操作。当我点击按钮时,鼠标左键表现正常,“left”不打印。 我错过了什么?提前谢谢!

    1 回复  |  直到 13 年前
        1
  •  2
  •   warvariuc    13 年前

    这对我来说很有效:

    # coding: utf-8
    import sys
    
    from PyQt4 import QtCore, QtGui
    
    
    class MyDialog(QtGui.QDialog):
        def __init__(self, parent=None):
            super(MyDialog, self).__init__(parent)
    
            self.button1 = QtGui.QPushButton("Button 1")
            self.button2 = QtGui.QPushButton("Button 2")
    
            hbox = QtGui.QHBoxLayout()
            hbox.addWidget(self.button1)
            hbox.addWidget(self.button2)
            self.setLayout(hbox)
    
            self.button1.clicked.connect(self.on_button_clicked)
            self.button2.clicked.connect(self.on_button_clicked)
    
            self.button1.installEventFilter(self)
    
        def eventFilter(self, obj, event):
            if event.type() in (QtCore.QEvent.MouseButtonPress,
                                QtCore.QEvent.MouseButtonDblClick):
                if event.button() == QtCore.Qt.LeftButton:
                    print "left"
                    return True
            return super(MyDialog, self).eventFilter(obj, event)
    
        def on_button_clicked(self):
            print('on_button_clicked')
    
    
    if __name__ == '__main__':
        app = QtGui.QApplication(sys.argv)
        w = MyDialog()
        w.show()
        sys.exit(app.exec_())
    
    推荐文章