#pragma execution_character_set("utf-8") #include "imageswitch.h" #include "qpainter.h" #include "qdebug.h" ImageSwitch::ImageSwitch(QWidget* parent) : QWidget(parent) { isChecked = false; setButtonStyle(ButtonStyle_1); this->setFixedSize(sizeHint()); } void ImageSwitch::mousePressEvent(QMouseEvent*) { imgFile = isChecked ? imgOffFile : imgOnFile; isChecked = !isChecked; this->update(); emit clicked(); } 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 {100, 50}; } QSize ImageSwitch::minimumSizeHint() const { return sizeHint(); } void ImageSwitch::setChecked(bool value) { if (this->isChecked != value) { this->isChecked = value; imgFile = isChecked ? imgOnFile : imgOffFile; this->update(); } } void ImageSwitch::setButtonStyle(const ImageSwitch::ButtonStyle& style) { if (this->buttonStyle != style) { this->buttonStyle = style; if (buttonStyle == ButtonStyle_1) { imgOffFile = ":/icons/imageswitch/btncheckoff1.png"; imgOnFile = ":/icons/imageswitch/btncheckon1.png"; this->resize(sizeHint()); } else if (buttonStyle == ButtonStyle_2) { imgOffFile = ":/icons/imageswitch/btncheckoff2.png"; imgOnFile = ":/icons/imageswitch/btncheckon2.png"; this->resize(sizeHint()); } else if (buttonStyle == ButtonStyle_3) { imgOffFile = ":/icons/imageswitch/btncheckoff3.png"; imgOnFile = ":/icons/imageswitch/btncheckon3.png"; this->resize(sizeHint()); } imgFile = isChecked ? imgOnFile : imgOffFile; setChecked(isChecked); this->update(); updateGeometry(); } }