-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImageButton.cpp
More file actions
103 lines (90 loc) · 2.17 KB
/
ImageButton.cpp
File metadata and controls
103 lines (90 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include "imagebutton.h"
#include <QtWidgets>
#include <QPixmap>
ImageButton::ImageButton(QString normalName, QString horverName, QString pressName,int icon_x,int icon_y,QWidget *parent)
: QPushButton(parent)
//设置按钮初始状态
, curStatus_(ST_INIT)
{
//设置按钮状态为正常
curStatus_ = ST_NORMAL;
//存储按钮三态图片
//正常图片
imageName_[ST_NORMAL] = normalName;
//悬停图片
imageName_[ST_HOVER] = horverName;
//按下图片
imageName_[ST_PRESS] = pressName;
//获得图片的大小以便用来调整按钮的大小
QPixmap icon;
icon.load(normalName);
this->icon_width=icon.width();
this->icon_height=icon.height();
this->setGeometry(icon_x,icon_y,icon_width,icon_height);
}
//按钮进入事件
void ImageButton::enterEvent(QEvent *)
{
if (curStatus_ == ST_INIT)
{
return;
}
curStatus_ = ST_NORMAL;
update();
}
//按钮离开事件
void ImageButton::leaveEvent(QEvent *)
{
if (curStatus_ == ST_INIT)
{
return;
}
curStatus_ = ST_NORMAL;
update();
}
//按钮按下事件
void ImageButton::mousePressEvent(QMouseEvent *event)
{
if (curStatus_ == ST_INIT)
{
return;
}
//如果鼠标左键点击
if (event->button() == Qt::LeftButton)
{
//将按钮状态设置为按下,并绘图
curStatus_ = ST_PRESS;
update();
}
}
//按钮释放事件
void ImageButton::mouseReleaseEvent(QMouseEvent *event)
{
//如果鼠标左键释放
if (event->button() == Qt::LeftButton)
{
if (curStatus_ != ST_INIT)
{
//将按钮状态设置为悬停,并绘图
curStatus_ = ST_HOVER;
update();
}
}
// 鼠标在弹起的时候光标在按钮上才激发clicked信号
if (rect().contains(event->pos()))
{
emit clicked();
}
}
//按钮样式绘图
void ImageButton::paintEvent(QPaintEvent *event)
{
if (curStatus_ == ST_INIT)
{
QPushButton::paintEvent(event);
return;
}
QPainter painter(this);
QPixmap pixmap(imageName_[curStatus_]);
painter.drawPixmap(rect(), pixmap);
}