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);
}