Qt绘制饼状图

必须在MainWindow.h头文件开头放

#include      //必须这么设置

创建chart:

void MainWindow::iniPiewChart()
{ //饼图初始化
    QChart *chart = new QChart();
    chart->setTitle(" Piechart演示");
    chart->setAnimationOptions(QChart::SeriesAnimations);
    ui->chartViewPie->setChart(chart);
    ui->chartViewPie->setRenderHint(QPainter::Antialiasing);
}

绘制chart:

void MainWindow::buildPieChart()
{ //绘制饼图
    QChart *chart =ui->chartViewPie->chart(); //获取chart对象
    chart->removeAllSeries(); //删除所有序列

    int colNo=1+ui->cBoxCourse->currentIndex(); //获取分析对象,数学、英语、语文或平均分

    QPieSeries *series = new QPieSeries(); //创建饼图序列
    series->setHoleSize(ui->spinHoleSize->value()); //饼图中间空心的大小

    for (int i=0;i<=4;i++) //添加分块数据
    {
        QTreeWidgetItem*  item=ui->treeWidget->topLevelItem(i); //获得QTreeWidgetItem的item
        series->append(item->text(0),item->text(colNo).toFloat()); //添加一个饼图分块数据,标签,数值
    }

    QPieSlice *slice; //饼图分块
    for(int i=0;i<=4;i++) //设置每个分块的标签文字
    {
        slice =series->slices().at(i);  //获取分块
        slice->setLabel(slice->label()+QString::asprintf(": %.0f人, %.1f%%",    //设置分块的标签
                        slice->value(),slice->percentage()*100));
//信号与槽函数关联,鼠标落在某个分块上时,此分块弹出
        connect(slice, SIGNAL(hovered(bool)),
                this, SLOT(on_PieSliceHighlight(bool)));
    }
    slice->setExploded(true); //最后一个设置为exploded
    series->setLabelsVisible(true); //只影响当前的slices,必须添加完slice之后再设置
    chart->addSeries(series); //添加饼图序列
    chart->setTitle("Piechart----"+ui->cBoxCourse->currentText());

    chart->legend()->setVisible(true); //图例
    chart->legend()->setAlignment(Qt::AlignRight);//Qt::AlignRight
}

设置chart样式:

ui->chartViewPie->chart()->setTheme(QChart::ChartTheme(index));

你可能感兴趣的:(qt,开发语言)