forked from feiyangqingyun/QWidgetDemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimageswitch.cpp
91 lines (77 loc) · 2.39 KB
/
imageswitch.cpp
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
#pragma execution_character_set("utf-8")
#include "imageswitch.h"
#include "qpainter.h"
#include "qdebug.h"
ImageSwitch::ImageSwitch(QWidget *parent) : QWidget(parent)
{
isChecked = false;
buttonStyle = ButtonStyle_2;
imgOffFile = ":/image/imageswitch/btncheckoff2.png";
imgOnFile = ":/image/imageswitch/btncheckon2.png";
imgFile = imgOffFile;
}
void ImageSwitch::mousePressEvent(QMouseEvent *)
{
imgFile = isChecked ? imgOffFile : imgOnFile;
isChecked = !isChecked;
this->update();
}
void ImageSwitch::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHints(QPainter::SmoothPixmapTransform);
QImage img(imgFile);
img = img.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
//按照比例自动居中绘制
int pixX = rect().center().x() - img.width() / 2;
int pixY = rect().center().y() - img.height() / 2;
QPoint point(pixX, pixY);
painter.drawImage(point, img);
}
bool ImageSwitch::getChecked() const
{
return isChecked;
}
ImageSwitch::ButtonStyle ImageSwitch::getButtonStyle() const
{
return this->buttonStyle;
}
QSize ImageSwitch::sizeHint() const
{
return QSize(87, 28);
}
QSize ImageSwitch::minimumSizeHint() const
{
return QSize(87, 28);
}
void ImageSwitch::setChecked(bool isChecked)
{
if (this->isChecked != isChecked) {
this->isChecked = isChecked;
imgFile = isChecked ? imgOnFile : imgOffFile;
this->update();
}
}
void ImageSwitch::setButtonStyle(const ImageSwitch::ButtonStyle &buttonStyle)
{
if (this->buttonStyle != buttonStyle) {
this->buttonStyle = buttonStyle;
if (buttonStyle == ButtonStyle_1) {
imgOffFile = ":/image/imageswitch/btncheckoff1.png";
imgOnFile = ":/image/imageswitch/btncheckon1.png";
this->resize(87, 28);
} else if (buttonStyle == ButtonStyle_2) {
imgOffFile = ":/image/imageswitch/btncheckoff2.png";
imgOnFile = ":/image/imageswitch/btncheckon2.png";
this->resize(87, 28);
} else if (buttonStyle == ButtonStyle_3) {
imgOffFile = ":/image/imageswitch/btncheckoff3.png";
imgOnFile = ":/image/imageswitch/btncheckon3.png";
this->resize(96, 38);
}
imgFile = isChecked ? imgOnFile : imgOffFile;
setChecked(isChecked);
this->update();
updateGeometry();
}
}