switchbutton.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <QPainter>
  2. #include <QPaintEvent>
  3. #include <QStyleOption>
  4. #include "switchbutton.h"
  5. SwitchButton::SwitchButton(QWidget* parent) : QPushButton(parent) {
  6. setCheckable(true);
  7. // Set default colors and labels
  8. setColors();
  9. setLabels();
  10. }
  11. void SwitchButton::setColors(const QColor on, const QColor off) {
  12. onColor=on;
  13. offColor=off;
  14. if (on.red()+on.green()+on.blue()>500) {
  15. onLabelColor=Qt::black;
  16. }
  17. else {
  18. onLabelColor=Qt::white;
  19. }
  20. if (off.red()+off.green()+off.blue()>500) {
  21. offLabelColor=Qt::black;
  22. }
  23. else {
  24. offLabelColor=Qt::white;
  25. }
  26. }
  27. void SwitchButton::setLabels(const QString on, const QString off) {
  28. onLabel=on;
  29. offLabel=off;
  30. setMinimumWidth(fontMetrics().width(offLabel)+fontMetrics().width(onLabel)+fontMetrics().height()*2);
  31. }
  32. void SwitchButton::paintEvent(QPaintEvent* paint) {
  33. QPushButton::paintEvent(paint);
  34. QPainter p(this);
  35. p.save();
  36. int rectWidth=paint->rect().width()/2;
  37. #ifdef Q_OS_ANDROID
  38. // On Android, the buttons are much smaller than paint->rect().
  39. int rectMargin=10;
  40. #else
  41. int rectMargin=4;
  42. #endif
  43. if (isChecked()) {
  44. QRect rect=paint->rect().adjusted(rectWidth,rectMargin,-rectMargin,-rectMargin);
  45. p.fillRect(rect,QBrush(onColor));
  46. QPoint textPosi=rect.center()-QPoint(fontMetrics().width(onLabel)/2,1-fontMetrics().ascent()/2);
  47. p.setPen(onLabelColor);
  48. p.drawText(textPosi,onLabel);
  49. }
  50. else {
  51. QRect rect=paint->rect().adjusted(rectMargin,rectMargin,-rectWidth,-rectMargin);
  52. p.fillRect(rect,QBrush(offColor));
  53. QPoint textPosi=rect.center()-QPoint(fontMetrics().width(offLabel)/2,1-fontMetrics().ascent()/2);
  54. p.setPen(offLabelColor);
  55. p.drawText(textPosi,offLabel);
  56. }
  57. p.restore();
  58. }