http://blog.csdn.net/zddblog/article/details/11116191

功能:鼠标弹起并在按键区域内时,按键响应。并实现normal、hover、pressed效果,PushButton大小默认为传入图片大小。

PushButton的normal、hover、pressed效果没有使用QSS实现,因为重写mouseReleaseEvent后,qss的hover效果混乱。

用法:

  1. loginButton = new PushButton(":/button/login_button_normal",
  2. ":/button/login_button_hover",
  3. ":/button/login_button_pressed");
    loginButton = new PushButton(":/button/login_button_normal",
":/button/login_button_hover",
":/button/login_button_pressed");

或者:

  1. loginButton = new PushButton(":/button/login_button");
    loginButton = new PushButton(":/button/login_button");

效果:

Qt 自定义PushButton-LMLPHP

具体实现:

  1. #include "pushbutton.h"
  2. #include <QPainter>
  3. #include <QMouseEvent>
  4. #include <QFontMetrics>
  5. #include <QLabel>
  6. PushButton::PushButton(QString normal, QString hover, QString pressed, QWidget *parent) :
  7. QPushButton(parent)
  8. {
  9. buttonState = Normal;
  10. normalPixmap.load(normal);
  11. hoverPixmap.load(hover);
  12. pressPixmap.load(pressed);
  13. this->setFixedSize(normalPixmap.size());
  14. this->setContentsMargins(0, 0, 0, 0);
  15. }
  16. PushButton::PushButton(QString background, QWidget *parent) :
  17. QPushButton(parent)
  18. {
  19. buttonState = Normal;
  20. normalPixmap.load(background);
  21. hoverPixmap.load(background);
  22. pressPixmap.load(background);
  23. this->setFixedSize(normalPixmap.size());
  24. this->setContentsMargins(0, 0, 0, 0);
  25. }
  26. void PushButton::paintEvent(QPaintEvent *)
  27. {
  28. QPainter painter(this);
  29. switch(buttonState)
  30. {
  31. case Normal:
  32. painter.drawPixmap(this->rect(), normalPixmap);
  33. break;
  34. case Hover:
  35. painter.drawPixmap(this->rect(), hoverPixmap);
  36. break;
  37. case Pressed:
  38. painter.drawPixmap(this->rect(), pressPixmap);
  39. }
  40. painter.drawText(this->rect(), Qt::AlignCenter, this->text());
  41. }
  42. void PushButton::enterEvent(QEvent *)
  43. {
  44. buttonState = Hover;
  45. update();
  46. }
  47. void PushButton::leaveEvent(QEvent *)
  48. {
  49. buttonState = Normal;
  50. update();
  51. }
  52. void PushButton::mousePressEvent(QMouseEvent *e)
  53. {
  54. if(e->button() == Qt::LeftButton)
  55. {
  56. buttonState = Pressed;
  57. update();
  58. }
  59. }
  60. bool isOnPushButton(const QPoint &point, const PushButton *pushButton)
  61. {
  62. if(point.x() < 0 || point.x() > pushButton->width() ||
  63. point.y() < 0 || point.y() > pushButton->height())
  64. {
  65. return false;
  66. }
  67. return true;
  68. }
  69. void PushButton::mouseReleaseEvent(QMouseEvent *e)
  70. {
  71. if(e->button() == Qt::LeftButton)
  72. {
  73. //判断鼠标抬起时是否在PushButton之上
  74. if(isOnPushButton(e->pos(), this))
  75. {
  76. emit clicked();
  77. }
  78. buttonState = Hover;
  79. update();
  80. }
  81. }
05-25 17:34