- 1 void KeyButton::paintEvent(QPaintEvent *event)
- 2 {
- 3 QPainter painter(this);
- 4 painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
- 5
- 6 //绘制背景+边框
- 7 painter.setPen(borderColor);
- 8 painter.setBrush(QColor(bgColor));
- 9 int min = qMin(this->rect().width(), this->rect().height());
- 10 int radius = min / 2;
- 11 //画圆角矩形
- 12 QPainterPath path;
- 13 QRect rect = this->rect();
- 14 path.moveTo(rect.bottomRight() - QPointF(0, radius));
- 15 path.lineTo(rect.topRight() + QPointF(0, radius));
- 16 path.arcTo(QRectF(QPointF(rect.topRight() - QPointF(radius * 2, 0)), QSize(radius * 2, radius *2)), 0, 90);
- 17 path.lineTo(rect.topLeft() + QPointF(radius, 0));
- 18 path.arcTo(QRectF(QPointF(rect.topLeft()), QSize(radius * 2, radius * 2)), 90, 90);
- 19 path.lineTo(rect.bottomLeft() - QPointF(0, radius));
- 20 path.arcTo(QRectF(QPointF(rect.bottomLeft() - QPointF(0, radius * 2)), QSize(radius * 2, radius * 2)), 180, 90);
- 21 path.lineTo(rect.bottomLeft() + QPointF(radius, 0));
- 22 path.arcTo(QRectF(QPointF(rect.bottomRight() - QPointF(radius * 2, radius * 2)), QSize(radius * 2, radius * 2)), 270, 90);
- 23 painter.drawPath(path);
- 24
- 25 QFont font = qApp->font();
- 26 font.setPixelSize(12);
- 27 painter.setFont(font);
- 28
- 29 //绘制文字
- 30 if (!text.isEmpty())
- 31 {
- 32 if(m_IsHover)
- 33 painter.setPen(hoverColor);
- 34 else
- 35 painter.setPen(textColor);
- 36 QRect textRect(padding * 1.5, 0, this->width(), this->height());
- 37 painter.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, text);
- 38 }
- 39 //绘制右侧图标
- 40 font.setPixelSize(15);
- 41 painter.setFont(font);
- 42 painter.drawText(rightRect, Qt::AlignHCenter | Qt::AlignVCenter, "X");
- 43 }