QT绘制饼图

QT版本:QT5.6.1

QT绘制饼图,出问题的代码如下

void DrawPieDialog::paintEvent(QPaintEvent *event)
{
    float startAngle=0;
    float spanAngle=( (qreal) (sell) / (qreal)(sell+last) ) *360;
    QPoint startPt(30,30);  //圆心
    QRect rect(startPt.x(), startPt.y(), 200, 200);
    QPainter p(this);
    int arcR = rect.width()/2;
    QPainterPath path;
    p.setBrush(Qt::green);

    path.moveTo(startPt.x() + arcR,startPt.y() + arcR);  //移动到圆心
    path.arcTo(rect,startAngle,spanAngle);
    p.drawPath(path);

    p.setBrush(Qt::red);
    path.moveTo(startPt.x() + arcR,startPt.y() + arcR);  //移动到圆心
    startAngle=spanAngle;
    spanAngle=360-startAngle;
    path.arcTo(rect,startAngle,spanAngle);
    p.drawPath(path);


    QRect rect2(250,175,20,20);
    QRect rect3(250,215,20,20);  //为了绘制方块用的变量
    //绘制方块
    p.setBrush(Qt::green);
    p.drawRect(rect2);
    p.setBrush(Qt::red);
    p.drawRect(rect3);
    //绘制文字
    p.drawText(QRectF(280,180,100,20),QString("已经销售的占比"));
    p.drawText(QRectF(280,220,100,20),QString("未销售的占比"));

}

解决办法:
1 使用更高版本的QT版本
 QT5.7以上版本支持QPieSeries + QPieSlice + QChart + QChartView等类,可以直接绘制饼图
2 修改代码如下

void DrawPieDialog::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    float startAngle=0;
    float spanAngle=( (qreal) (sell) / (qreal)(sell+last) ) *360;

    QPoint startPt(30,30);  //圆心
    QRect rect(startPt.x(), startPt.y(), 200, 200);
    int arcR = rect.width()/2;
    QList colorList;

    for(int i = 0; i < 2; i++)
    {
        //生成随机颜色并过滤掉白色
        int colorR, colorG, colorB;
        while (1)
        {
            colorR = rand() % 256;
            colorG = rand() % 256;
            colorB = rand() % 256;

            if (colorR == 255 && colorG == 255 && colorB == 255)
            {
                continue;
            }
            else
            {
                break;
            }
        }
        QColor color(colorR, colorG, colorB);
        colorList.append(color);
        painter.setBrush(QBrush(color));
        //画扇形
        QPainterPath path;
        path.moveTo(startPt.x() + arcR,startPt.y() + arcR);  //移动到圆心
        if(i == 1)
        {
            startAngle=spanAngle;
            spanAngle=360-spanAngle;
        }
        path.arcTo(rect, startAngle, spanAngle);
        painter.drawPath(path);
    }  //end for
}

 绘图光滑需要设置:
painter.setRenderHint(QPainter::Antialiasing, true);
 效果图如下
QT绘制饼图_第1张图片

3 修改代码如下

参考资料
1 Qt之饼图 https://www.cnblogs.com/xinxue/p/6021873.html
2 Qt4.8.5以上版本绘制饼图 https://blog.csdn.net/Pailugou/article/details/82080829
3 关于QT的QPainterPath::arcTo 详解 https://www.cnblogs.com/yuzhould/p/9132493.html

转载于:https://www.cnblogs.com/Manual-Linux/p/10153918.html

你可能感兴趣的:(QT绘制饼图)