liudianwu |
2020-06-15 08:55 |
Qt开源作品33-图片开关控件
## 一、前言 进入智能手机时代以来,各种各样的APP大行其道,手机上面的APP有很多流行的元素,开关按钮个人非常喜欢,手机QQ、360卫士、金山毒霸等,都有很多开关控制一些操作,在WINFORM项目上,如果将CheckBox也改为开关按钮,估计也会为项目增添不少新鲜感。 沿袭之前的做法,本人还是喜欢直接PS好图片后,用drawimage方法将图片绘制到用户控件上,启用双缓冲和背景透明,有些人说PS一张精美的图片也不是很容易,需要专业的,这里提供一个好方法,让你也可以获取到这些图片,其实大部分的APP都可以用解压软件打开,拓展名改为.zip即可,解压出来一般里面都含有绝大部分的图片,发现绝大部分的APP都喜欢用图片作为背景来展示一些效果,而不是原原本本的用代码一点点绘制。腾讯就是腾讯啊,大公司!人家的美工MM设计的图片那真的没得话说,绝对一流,手机QQ每次升级一个版本,都会下过来将里面的精美图片图标之类的提取出来,以便项目使用,这不会算是盗版吧!
## 二、代码思路 ```c++ ImageSwitch::ImageSwitch(QWidget *parent) : QWidget(parent) { isChecked = false; buttonStyle = ButtonStyle_2;
imgOffFile = ":/image/btncheckoff2.png"; imgOnFile = ":/image/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/btncheckoff1.png"; imgOnFile = ":/image/btncheckon1.png"; this->resize(87, 28); } else if (buttonStyle == ButtonStyle_2) { imgOffFile = ":/image/btncheckoff2.png"; imgOnFile = ":/image/btncheckon2.png"; this->resize(87, 28); } else if (buttonStyle == ButtonStyle_3) { imgOffFile = ":/image/btncheckoff3.png"; imgOnFile = ":/image/btncheckon3.png"; this->resize(96, 38); }
imgFile = isChecked ? imgOnFile : imgOffFile; setChecked(isChecked); this->update(); updateGeometry(); } } ```
## 三、效果图 [attachment=21674]
|
|