当前位置:网站首页>【Qt 教程】QPushButton 按键和双击效果
【Qt 教程】QPushButton 按键和双击效果
2022-06-29 13:53:00 【技术美术狂热分子】
原文链接:https://www.xingyulei.com/post/qt-detect-click/
Introduction
I want to showcase some examples that I used to create push button with
custom behaviours.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tBV4vegt-1655954792798)(https://i.imgur.com/e2LbhNJ.gif)]
(Double click button)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ccRDk21c-1655954917368)(https://i.imgur.com/FCzg1MQ.gif)]
(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()
class MyButton(QtWidgets.QPushButton):
right_clicked = QtCore.Signal()
left_clicked = QtCore.Signal()
double_clicked = QtCore.Signal()
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.timer = QtCore.QTimer()
self.timer.setSingleShot(True)
self.timer.setInterval(250)
self.timer.timeout.connect(self.timeout)
self.is_double = False
self.is_left_click = True
self.installEventFilter(self)
self.double_clicked.connect(self.double_click_event)
self.left_clicked.connect(self.left_click_event)
self.right_clicked.connect(self.right_click_event)
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.MouseButtonPress:
if not self.timer.isActive():
self.timer.start()
self.is_left_click = False
if event.button() == QtCore.Qt.LeftButton:
self.is_left_click = True
return True
elif event.type() == QtCore.QEvent.MouseButtonDblClick:
self.is_double = True
return True
return False
def timeout(self):
if self.is_double:
self.double_clicked.emit()
else:
if self.is_left_click:
self.left_clicked.emit()
else:
self.right_clicked.emit()
self.is_double = False
def left_click_event(self):
print('left clicked')
def right_click_event(self):
print('right clicked')
def double_click_event(self):
print('double clicked')
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.
right_clicked = QtCore.Signal()
left_clicked = QtCore.Signal()
double_clicked = QtCore.Signal()
This enhanced the usability of the click behaviour, meaning that this extendedQPushbutton 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.
btn = MyButton('Button1')
btn.doubled_clicked.connect(func1)
btn.right_clicked.connect(func2)
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.
class HoverBtn(QtWidgets.QLabel):
clicked = QtCore.Signal(QtCore.QObject)
def __init__(self, parent):
super(HoverBtn, self).__init__(parent)
style = """ QFrame{ border-radius: 25px; border-width: 2px; border-style: solid; border-color: rgb(20, 20, 20); background-color: rgb(170, 170, 170); } """
self.installEventFilter(self)
self.setStyleSheet(style)
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.Enter:
self.set_outline(1)
return True
elif event.type() == QtCore.QEvent.Leave:
self.set_outline(0)
return True
if event.type() == QtCore.QEvent.MouseButtonPress \
and event.button() == QtCore.Qt.LeftButton:
self.clicked.emit(self)
return True
return False
def set_outline(self, status):
""" Update widget stylesheet when highlight """
style = self.styleSheet()
border_pattern = r'border-color\: rgb\(\d+, \d+, \d+\)'
dark = 'border-color: rgb(20, 20, 20)'
light = 'border-color: rgb(21, 255, 9)'
if status == 1:
style = re.sub(border_pattern, light, style)
elif status == 0:
style = re.sub(border_pattern, dark, style)
self.setStyleSheet(style)
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.
Reference
边栏推荐
- goby全端口扫描
- Follow me study hcie big data mining Chapter 1 Introduction to data mining module 1
- Equivalence class partition method for test case design method
- Distributed cache for memcached
- unity吃豆人小游戏,迷宫实现
- 【VEUX开发者工具的使用-getters使用】
- Installation and removal of cover for CPU protection on desktop motherboard
- HTAP X 云原生: TiDB 加速释放数据价值,实现数据敏捷
- MySQL数据库:存储引擎
- urllib urllib2
猜你喜欢

Mondo rescue creates an image file (which is conducive to image damage recovery)

How goby exports scan results

vmware虚拟机的作用

数字IC手撕代码--交通灯
![[dark horse morning post] the market value of China public education has evaporated by more than 200billion; New Oriental has more than 20million live fans; HM closes its first store in China; Vanke Y](/img/d7/4671b5a74317a8f87ffd36be2b34e1.jpg)
[dark horse morning post] the market value of China public education has evaporated by more than 200billion; New Oriental has more than 20million live fans; HM closes its first store in China; Vanke Y

Hardware development notes (VIII): basic process of hardware development, making a USB to RS232 module (VII): creating a basic dip component (crystal oscillator) package and associating the principle

微信小程序:万圣节头像框生成工具

NuScenes关于Radar的配置信息

go-zero微服务实战系列(七、请求量这么高该如何优化)

Crazy digital collections, the next myth of making wealth?
随机推荐
中康控股开启招股:拟募资净额3.95亿港元,预计7月12日上市
灵感收集·创意写作软件评测:Flomo、Obsidian Memo、Napkin、FlowUs
tcpdump如何对特定的tcp标志位进行过滤
超 Nice 的表格响应式布局小技巧
Crazy digital collections, the next myth of making wealth?
TikTok全球短视频霸主地位或被YouTube反超
靠代理,靠买断,国产端游的蛮荒时代等待下一个《永劫无间》
Redis主从复制原理
[high concurrency] 28000 words' summary of callable and future interview knowledge points. After reading it, I went directly to ByteDance. Forgive me for being a little drifting (Part 1)
Shell——文本处理命令
Redis为什么这么快?Redis是单线程还是多线程?
Teach you how to install the latest version of mysql8.0 database on windows, nanny level teaching
Thanos Store 组件
What is the reason why the gbase8s database encountered a 951 error?
“死掉”的诺基亚,一年躺赚1500亿
urllib urllib2
分布式唯一 ID 生成方案浅谈
Unity SplashImage 缩放问题
微信小程序:图片秒加水印制作生成
微信小程序:修复采集接口版云开发表情包