QPieSeries-饼状图

void Widget::initWindowQPie()
{

    //[1] 创建饼图
    QPieSeries* pSeries = new QPieSeries();
    pSeries->append("苹果", 15);
    pSeries->append("西瓜", 30);
    pSeries->append("香蕉", 10);
    pSeries->append("葡萄", 25);
    pSeries->append("榴莲", 20);


    //[2] 表示饼系列中的单个切片
    qreal total = 0; //qreal 是一个用于表示浮点数的数据类型
    qDebug() << pSeries->slices().size();
    for (int i = 0; i < pSeries->slices().size(); i++)
    {
        total += pSeries->slices().at(i)->value();
        qDebug()<< "test->total:" << total;
    }

    QList<QColor> colors = {Qt::red, Qt::green, Qt::yellow, Qt::blue, Qt::magenta};
    int colorIndex = 0;

    foreach (QPieSlice *slice, pSeries->slices())
    {

        // 每个切换设置颜色
        QColor color = colors[colorIndex % colors.size()]; // 循环使用颜色列表
        slice->setColor(color);

        qDebug() << "slice->value" << slice->value();
        qreal percentage = (slice->value() / total) * 100;
        slice->setLabel(QString("%1 (%2%)").arg(slice->label()).arg(percentage, 0, 'f', 1));
        // 此属性保留切片标签的可见性
        slice->setLabelVisible(true);

        colorIndex++;
    }


    QPieSlice *slice = pSeries->slices().at(1);
    // 此属性用于保存切片是否与饼图分离

    slice->setExploded(true);
    slice->setPen(QPen(Qt::darkGreen, 0));
    slice->setBrush(Qt::green);
    //![2]


    //![3] 创建图表
    QChart *chart = new QChart();
    chart->addSeries(pSeries);
    chart->setTitle("水果消费量");
    chart->legend()->hide();
    //![3]

    //![4] 图表视图
    QChartView *chartView = new QChartView();

    chartView->setChart(chart);

    chartView->setRenderHint(QPainter::Antialiasing);
    //![4]


    QVBoxLayout* pLayout = new QVBoxLayout(this);
    pLayout->addWidget(chartView);


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值