Rename file imageswitch.h & imageswitch.cpp to ImageSwitch.h & ImageSwitch.cpp, and refactor.

This commit is contained in:
Krad
2022-06-07 15:17:12 +08:00
parent 9c5838eaf8
commit c37d1134a6
4 changed files with 82 additions and 152 deletions

View File

@@ -0,0 +1,54 @@
#include "ImageSwitch.h"
#include <qpainter.h>
#include <qdebug.h>
namespace{
const int DEFAULT_WIDTH = 100;
const int DEFAULT_HEIGHT = 50;
const char * const OFF_FILE_PATH = ":/icons/imageswitch/btncheckoff1.png";
const char * const ON_FILE_PATH = ":/icons/imageswitch/btncheckon1.png";
}
ImageSwitch::ImageSwitch(QWidget* parent)
: QWidget(parent)
, mIsChecked(false)
, mImgOffFile(OFF_FILE_PATH)
, mImgOnFile(ON_FILE_PATH)
{
this->resize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
this->setMinimumSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
void ImageSwitch::mousePressEvent(QMouseEvent*)
{
mIsChecked = !mIsChecked;
this->update();
emit clicked();
}
void ImageSwitch::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.setRenderHints(QPainter::SmoothPixmapTransform);
QImage img(mIsChecked ? mImgOffFile : mImgOnFile);
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 mIsChecked;
}
void ImageSwitch::setChecked(bool value) {
if (this->mIsChecked == value) return;
this->mIsChecked = value;
this->update();
}