Nathan
Nathan

Reputation: 11

PyQt Python - Creating right mouse click for QPushButton

I'm dynamically creating creating a list of QPushButtons in a vertical layout. I'm currently using the "click" signal for a function. But I would like to use the right mouse button for an additional function. Ex. print the tooltip of that QPushButton that the mouse is over by right clicking.

but = QtGui.QPushButton()
but.setText(cur);but.setCheckable(True)
but.setStyleSheet(_fromUtf8("text-align:right;background-color: rgb(50, 50, 50);"))
but.setToolTip(longName + "." + cur)

I'm looking over at the "QMouseEvent", "setMouseTracking", "mousePressEvents". But I'm not sure how to properly use them to get my desired result. I would also be open to a custom signal for a QPushButton on "right-click".

Upvotes: 1

Views: 12146

Answers (2)

ekhumoro
ekhumoro

Reputation: 120768

You can check the mouse buttons in your handler for the clicked signal:

    but.clicked.connect(self.buttonClicked)
    ...

def buttonClicked(self):
    if QApplication.mouseButtons() & QtCore.Qt.RightButton:
        print(self.sender().toolTip())

The mouse button constants can be OR'd together, allowing you to test for different combinations of them. So the above code will detect that the right button is held down while the left button is clicked.

You can also do a similar thing with the keyboard modifiers:

    if QApplication.keyboardModifiers() & QtCore.Qt.ControlModifier:
        print('ctrl+click')

Upvotes: 4

tynn
tynn

Reputation: 39873

Usually, the right mouse click is connected to the context menu. With

but.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
but.customContextMenuRequested.connect(handle_right_click)

you can connect a handler, which could be used for the right mouse click.

If you'd like to have a pure right mouse click action, you should extend QPushButton and override mousePressEvent(self, event) and mouseReleaseEvent(self, event). Then you need to set the button's ContextMenuPolicy to QtGui.Qt.PreventContextMenu to ensure their delivery:

The widget does not feature a context menu, and in contrast to NoContextMenu, the handling is not deferred to the widget's parent. This means that all right mouse button events are guaranteed to be delivered to the widget itself through QWidget::mousePressEvent(), and QWidget::mouseReleaseEvent().

Upvotes: 4

Related Questions