siria
siria

Reputation: 309

Detect single mouse click in PyQt5 Widgets - missing mouseClickEvent function

I would like to recognize a single mouse click over a QWidget in PyQt5. In the docs there is either mouseDoubleClickEvent or mousePressEvent but there is no mouseClickEvent function for a single click. How do I get that functionality? Thank you

BTW I've noticed PyQtGraph does have a mouseClickEvent function.

Upvotes: 5

Views: 8183

Answers (1)

musicamante
musicamante

Reputation: 48231

Qt doesn't provide a "click" event on its own, you have to implement such a feature based on mousePressEvent and mouseReleaseEvent, by checking that the release has happened within the geometry of the widget (and, possibly, that the correct mouse button was pressed and released).

class ClickWidget(QWidget):
    pressPos = None
    clicked = pyqtSignal()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.pressPos = event.pos()

    def mouseReleaseEvent(self, event):
        # ensure that the left button was pressed *and* released within the
        # geometry of the widget; if so, emit the signal;
        if (self.pressPos is not None and 
            event.button() == Qt.LeftButton and 
            event.pos() in self.rect()):
                self.clicked.emit()
        self.pressPos = None

Upvotes: 7

Related Questions