cpp
//Chart.h
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_Chart.h"
#include <QtCharts/QChartView>
#include <QtCharts/QPieSeries>
#include <QtCharts/QPieSlice>
#include <QVBoxLayout>
using namespace QtCharts;
class Chart : public QMainWindow
{
Q_OBJECT
public:
Chart(QWidget *parent = nullptr);
~Chart();
private:
Ui::ChartClass ui;
QPieSeries* pie_series;
};
cpp
//Chart.cpp
#include "Chart.h"
Chart::Chart(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
//饼状图
pie_series = new QPieSeries(this);
connect(pie_series, SIGNAL(clicked(QPieSlice*)), this, SLOT(onPieSeriesClicked(QPieSlice*)));
//定义各扇形切片的颜色
static const QStringList list_pie_color = {
"#F51F48","#225AE7","#F3BA0C","#808080",
};
//设置数据
QList<qreal> list_data = { 239, 171, 114, 59 };
//扇形
for (int i = 0; i < list_pie_color.size(); i++) {
QPieSlice* pie_slice = new QPieSlice(this);
pie_slice->setLabelVisible(true);
pie_slice->setValue(list_data[i]);
pie_slice->setLabel(QString::number(list_data[i]));
pie_slice->setColor(list_pie_color[i]);
pie_slice->setLabelColor(list_pie_color[i]);
pie_slice->setBorderColor(list_pie_color[i]);
pie_series->append(pie_slice);
//设置是否显示扇形切片的标签
pie_series->setLabelsVisible(false);
}
//设置饼状图的内部空心大小为 0.5
pie_series->setHoleSize(0.5);
//图表视图
QChart* chart = new QChart;
chart->setTitle(u8"");
//设置暗黑主题
chart->setTheme(QChart::ChartThemeLight);
chart->setBackgroundVisible(false);
//标题字体
QFont font = qApp->font();
font.setBold(true);
font.setPointSize(10);
chart->setTitleFont(font);
//加入饼图
chart->addSeries(pie_series);
chart->setAnimationOptions(QChart::SeriesAnimations);
//图例
//设置图例的位置在底部
chart->legend()->setAlignment(Qt::AlignBottom);
//设置图例是否可见
chart->legend()->setVisible(false);;
//加入绘画视图
QChartView* chartView = new QChartView(this);
chartView->setRenderHint(QPainter::Antialiasing);
chartView->setChart(chart);
chartView->setStyleSheet("background-color: transparent;");
chartView->resize(800, 600);
//加入布局
QVBoxLayout* layout = new QVBoxLayout;
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(chartView);
ui.centralWidget->setLayout(layout);
ui.centralWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
Chart::~Chart()
{}
推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家:
零声白金学习卡(含基础架构/高性能存储/golang云原生/音视频/Linux内核)
https://xxetb.xet.tech/s/3Zqhgt