Introduction
I want to showcase some examples that I used to create push button with custom behaviours.
(Double click button)
(Button hover effect)
Double Click
Problem with MouseButtonDblClick
Hey, I thought this would be easy, since Qt offers a built-in event
type: QEvent.MouseButtonDblClick
.
But the issue is it couldn’t distinguish a single click vs. a double click.
Which means, the single click event will also be invoked when double-clicked.
Solution using timeout
Subclass QPushButton
and override eventFilter()
Using eventFilter()
eventFilter()
takes three argument, a QObject
that the filter is installed
on, a QObject
that is being watched, and a reference to a QEvent
type object
to be filtered.
Be sure to add self.installEventFilter(self)
so to override event filtering.
Now it’s only the matter of adding condition logic to filter out different
event types such as QEvent.MouseButtonPress
and QEvent.MouseButtonDblClick
with event.type()
We can also filter which button is being used using event.button()
.
timeout
Using a built-in timer from Qt QTimer()
, we are able to fire off timer
events between our clicks.
A timeout
signal is fired after a certain interval we defined using setInterval()
.
the timeout()
method is then used to determine what custom signal to emit.
Custom Signal
Note that I created three custom signals for three different clicking type I want to register.
1 | right_clicked = QtCore.Signal() |
This enhanced the usability of the click behaviour, meaning that this extended
QPushbutton
can tell whether the user did a single left or right click or a
double click.
In my example above, I wrapped all the click events in the class itself.
But in the main application, we can also instantiate MyButton
and connect click event
to method of our choice.
1 | btn = MyButton('Button1') |
Hover Effect
As a bonus, I want to include a “Button” with custom hover effect, but it is
technically a QLabel
object with extended functionality, which is being used
in my SnapTool.
1 | class HoverBtn(QtWidgets.QLabel): |
The hover effect is achieved by swapping stylesheet properties, and the rest of the event filtering is very similar to the previous double click button.