QT之“飞镖盘”自定义控件
- 前言
- 控件预览
- 实现
前言
现在发一个我之前看过有人写了一个抽奖转盘,所以闲来无事写了一个飞镖盘控件,在我看来它其它没有什么实用价值,纯属写来玩玩而已。
控件预览
实现
- 画背景
void QDartboard::drawBkg(QPainter *painter,)
{int radius = 95;painter->save();painter->setBrush(bkgColor);painter->drawEllipse(-radius, -radius, radius << 1, radius << 1);painter->restore();
}
- 画扇形
void QDartboard::drawFans(QPainter *painter)
{float rad = 0;float panAngle = 360 / fanNum;int radius = 80;for(int i = 1; i <= fanNum; i++){if(i % 2 == 0){gradientArc(painter, radius, rad + panAngle * i, panAngle, qRgb(200, 0, 0));gradientArc(painter, radius - ringSize, rad + panAngle * i, panAngle, qRgb(0, 200, 0));gradientArc(painter, radius - 30, rad + panAngle * i, panAngle, qRgb(200, 0, 0));gradientArc(painter, radius - 30 - ringSize, rad + panAngle * i, panAngle, qRgb(0, 200, 0));}else{gradientArc(painter, radius, rad + panAngle * i, panAngle, qRgb(0, 200, 0));gradientArc(painter, radius - ringSize, rad + panAngle * i, panAngle, qRgb(200, 0, 0));gradientArc(painter, radius - 30, rad + panAngle * i, panAngle, qRgb(0, 200, 0));gradientArc(painter, radius - 30 - ringSize, rad + panAngle * i, panAngle, qRgb(200, 0, 0));}}gradientArc(painter, radius - 70, 0, 360, qRgb(0, 200, 0));gradientArc(painter, radius - 75, 0, 360, qRgb(200, 0, 0));
}void QDartboard::gradientArc(QPainter *painter, int radius, int startAngle, int angleLength, QRgb color)
{painter->save();// 渐变色//QRadialGradient gradient(0, 0, radius);//gradient.setColorAt(0, Qt::white);//gradient.setColorAt(1.0, color);//painter->setBrush(QColor(color));//painter->setPen(color);// << 1(左移1位)相当于radius*2 即:150*2=300//QRectF(-150, -150, 300, 300)QRectF rect(-radius, -radius, radius << 1, radius << 1);QPainterPath path;path.arcTo(rect, startAngle, angleLength);painter->setPen(Qt::NoPen);painter->drawPath(path);painter->fillPath(path, QBrush(QColor(color)));painter->restore();
}
- 画刻度值
void QDartboard::drawScaleNum(QPainter *painter)
{int radius = 85;painter->save();painter->setPen(Qt::white);QFont font("Arial", 6, QFont::Bold, false);//设置字体的类型,大小,加粗,斜体painter->setFont(font);painter->rotate(90 + ((360 / fanNum) / 2));for (int i = 1; i <= fanNum; i++){QString strValue = QString("%1").arg(i);double textWidth = fontMetrics().width(strValue);//double textHeight = fontMetrics().height();painter->rotate(-360 / fanNum);painter->drawText(0 - textWidth / 2, -radius, strValue);}painter->restore();
}