speedyTeh
speedyTeh

Reputation: 257

PyQT: Disabling left mouse click

is there a way to disable (and override) left mouse click in Qt? Even better, in PyQt.I wrote something like this inside my widget class:

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

an also triedthis:

    def eventFilter(self, source, event):

        if event.type()==QtCore.QEvent.MouseButtonPress:
            if event.button() == QtCore.Qt.LeftButton:
                print "left"

...
app.installEventFilter(ui)

But this is executed only if I click somewhere where left click does nothing, e.g. on form background. When i click on pushbutton, the left mouse button behaves normaly and "left" isn't printed. What am I missing? Thanks in advance!

Upvotes: 0

Views: 5225

Answers (1)

warvariuc
warvariuc

Reputation: 59674

This works for me:

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

Upvotes: 2

Related Questions