55 lines
1.3 KiB
C++
55 lines
1.3 KiB
C++
|
|
#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();
|
||
|
|
}
|