QT += core gui charts
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QLabel>
#include <QtCharts>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void resizeEvent(QResizeEvent *event);
QLabel *m_centerLabel;
QChartView *b;
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
QT_CHARTS_USE_NAMESPACE
#include "ui_widget.h"
#include <QtWidgets>
#include <QtCharts>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
QGridLayout *a=new QGridLayout;
ui->ycn->setLayout(a);
b=new QChartView;
a->addWidget(b);
QPieSeries* series = new QPieSeries(); // 创建一个圆环图对象
series->setHoleSize(0.45); // 设置圆环孔径大小0.0 ~1.0
series->append("蛋白质占比 9.2%", 9.2); // 将具有指定值和标签的单个切片附加到series
series->append("其它 23.8%", 23.8);
series->append("碳水化合物 51.4%", 51.4);
QPieSlice* slice = series->append("脂肪占比 15.6%", 15.6); // 设置一个圆环切片,并返回这个切片对象
slice->setExploded(); // 将当前切片分离
slice->setLabelVisible(); // 显示当前切片的标签,默认是不显示的
b->setRenderHint(QPainter::Antialiasing); // 设置抗锯齿
b->chart()->setTitle("圆环图标题"); // 设置图表标题
b->chart()->addSeries(series); // 将创建的圆环对象添加进chart中
b->chart()->setTheme(QChart::ChartThemeBlueCerulean); // 设置图表的样式
b->chart()->legend()->setAlignment(Qt::AlignBottom); // 指定图例显示在图表底部
b->chart()->legend()->setFont(QFont("Arial", 12)); // 设置图例的字体
m_centerLabel = new QLabel("80%", b);
m_centerLabel->setStyleSheet(QString("background:transparent;font-family:\"Mircsoft Yahei\";"
"font-size:20px; color:#1564FF; font-weight:bold;"));
// m_centerLabel->hide();
}
void Widget::resizeEvent(QResizeEvent *event)
{
m_centerLabel->move(b->width()/2+m_centerLabel->width()/2,
b->height()/2);
}
Widget::~Widget()
{
delete ui;
}