QT绘制同心扇形

发布于:2024-12-19 ⋅ 阅读:(10) ⋅ 点赞:(0)
void ChartForm::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);// 设置抗锯齿
    painter.save();

    // 设置无边框(不需要设置QPen,因为默认是不绘制边框的)
    QPen pen(Qt::NoPen);
    // QPen pen(Qt::black, 1);
    painter.setPen(pen);

    QRect rect;

    int step = 50;          // 内圈和外圈的距离
    int sRange = 8;         // 扇形向外绘制的范围(圈数)
    int numSlices = 16;     // 分成多少个扇形
    int lenght = 2 * step;  // 矩形边长
    // 计算扇形的中心点、半径、起始角度和跨度角度
    int centerX = width() / 2;
    int centerY = height() / 2;

    // 生成颜色(这里简单地使用彩虹色)
    QVector<QColor> colors;
    for (int i = 0; i <= sRange; ++i)
    {
        float hue = (float)i / sRange * 360.0f;
        colors.append(QColor::fromHsvF(hue / 360.0f, 1.0f, 1.0f));
    }

    // 绘制每个扇形
    for (int i = 0; i < numSlices; ++i)
    {
        double startAngle = i * 360.0f / numSlices;
        double spanAngle = 360.0f / numSlices;

        for(int idx = 1; idx <= sRange; idx ++)
        {
            QPoint startPt(centerX - idx * step, centerY - idx * step);
            rect.setRect(startPt.x(), startPt.y(), lenght + idx * lenght, lenght + idx * lenght);// 外圈

            int inRadius = idx * lenght;

            QRectF innerRect(startPt.x() + step, startPt.y() + step,inRadius,inRadius);// 内圈

            QPointF outStartPoint;
            outStartPoint.rx() += rect.center().x();
            outStartPoint.ry() = rect.center().y() - outStartPoint.y();

            QPainterPath path;// 创建一个QPainterPath对象
            path.moveTo(outStartPoint); //先移动到圆心
            path.arcTo(rect, startAngle, spanAngle);// 参数(矩形左上角坐标,弧的宽度,弧的高度,起始角,画多少度)
            path.arcTo(innerRect, startAngle + spanAngle, -spanAngle);// 参数(矩形左上角坐标,弧的宽度,弧的高度,起始角,画多少度)
            path.closeSubpath(); // 闭合路径(可选)
            painter.setBrush(colors[idx]);
            painter.drawPath(path);
        }
    }
    painter.restore();
}

执行结果如下图所示: