0

有没有办法在 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)

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

4

1 回答 1

2

这对我有用:

# 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_())
于 2013-04-26T10:00:45.423 回答