Qt 画自定义饼图统计的例子

先给出结果图,这个例子是将各种事件分类然后统计的其比例,然后画饼图显示出来

这个是我仿照官方给的例子,让后自己理解后,修改的,要生成饼图,需要QT的 charts 支持,安装QT 没有选择这个的,需要下载这个模块,然后在.pro文件中年添加

QT += charts

首先重写饼图块,让鼠标悬浮在某个饼图块时,让这个块弹出来,然后显示块的信息,这个比较简单,如下所示

//头文件
#include <QtCharts/QPieSlice>QT_CHARTS_USE_NAMESPACEclass CustomSlice : public QPieSlice
{Q_OBJECTpublic:CustomSlice(QString label, qreal value);public Q_SLOTS:void showHighlight(bool show);};//cpp文件#include "customslice.h"QT_CHARTS_USE_NAMESPACECustomSlice::CustomSlice(QString label, qreal value): QPieSlice(label, value)
{connect(this, &CustomSlice::hovered, this, &CustomSlice::showHighlight);
}void CustomSlice::showHighlight(bool show)
{setLabelVisible(show);//显示标签setExploded(show); // 弹出
}

主体代码如下,主要是初始化饼图,创建饼图,为饼图块随机上色,为饼图数据的显示做排序,只需要调用接口函数把相应的数据塞进去即可生成可视化的饼图

statisticwindow.h

#ifndef STATISTICCHARTSWINDOW_H
#define STATISTICCHARTSWINDOW_H#include <QWidget>
#include <QVBoxLayout>
#include <QtCharts/QPieSeries>
#include <QtCharts/QBarCategoryAxis>
#include <QtCharts/QValueAxis>
#include <QtCharts/QChartView>class QPushButton;
class CustomSlice;
QT_CHARTS_USE_NAMESPACEclass StatisticChartsWindow : public QWidget
{Q_OBJECT
public:explicit StatisticChartsWindow(QWidget *parent = nullptr);~StatisticChartsWindow();//创建一个饼图1void createPie1(QMap<QString, int> data, QString title);//创建一个饼图2void createPie2(QMap<QString, int> data, QString title);// 为饼图1添加块信息void appendSlice1(QString lable, int value);// 为饼图2添加块信息void appendSlice2(QString lable, int value);// 移除所有块信息void removeAllSlice();// 获取随机颜色为饼图的每个块上色Qt::GlobalColor getRandomColor();//获取排序后的数据QList<QMap<QString, int>> getsortListByValue(QMap<QString, int> &data);QVBoxLayout *VBoxLayout;QPieSeries *series1;QPieSeries *series2;QChart *chart1;QChart *chart2;QChartView *chartView1;QChartView *chartView2;QPushButton *closeButton;QList<CustomSlice*> CustomSlice1List;QList<CustomSlice*> CustomSlice2List;QList<Qt::GlobalColor> colorList;signals:void closeSig();public slots:
};#endif // STATISTICCHARTSWINDOW_H

statisticwindow.cpp

#include "statisticwindow.h"
#include <QtCharts/QBarSeries>
#include <QtCharts/QBarSet>
#include <QtCharts/QLegend>
#include <QtCharts/QPieSeries>
#include <QtCharts/QBarCategoryAxis>
#include <QtCharts/QValueAxis>
#include <QtCharts/QChartView>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSpacerItem>
#include <QRandomGenerator>
#include "customslice.h"
#include <QPushButton>
#include "pushbutton.h"StatisticChartsWindow::StatisticChartsWindow(QWidget *parent) : QWidget(parent)
{VBoxLayout = new QVBoxLayout(this);series1 = new QPieSeries(this);// 饼图一chart1 = new QChart();chart1->setAnimationOptions(QChart::AllAnimations);chart1->legend()->setVisible(true);chart1->legend()->setAlignment(Qt::AlignRight);//设置标签在右侧chartView1 = new QChartView(chart1);series2 = new QPieSeries(this);// 饼图一chart2 = new QChart();chart2->setAnimationOptions(QChart::AllAnimations);chart2->legend()->setVisible(true);chart2->legend()->setAlignment(Qt::AlignRight);//设置标签在右侧chartView2 = new QChartView(chart2);//底部添加关闭按钮closeButton = new QPushButton("关闭", this);QHBoxLayout *hlayout = new QHBoxLayout();hlayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));hlayout->addWidget(closeButton);hlayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));//SC3C::Valwell::PushButton::initStyle(closeButton);QPalette palette = closeButton->palette();QColor color(19, 46, 74); // RGB红色palette.setColor(QPalette::Button, color);closeButton->setPalette(palette);closeButton->setStyleSheet("color: white;");colorList<<Qt::red<<Qt::white<<Qt::darkGray<<Qt::gray<<Qt::lightGray<<Qt::red<<Qt::green<<Qt::blue<<Qt::cyan<<Qt::magenta<<Qt::yellow<<Qt::darkRed<<Qt::darkGreen<<Qt::darkBlue<<Qt::darkCyan;chartView1->chart()->setTheme(QChart::ChartThemeBlueCerulean);chartView2->chart()->setTheme(QChart::ChartThemeBlueCerulean);VBoxLayout->addWidget(chartView1);VBoxLayout->addWidget(chartView2);VBoxLayout->addLayout(hlayout);VBoxLayout->layout()->setSpacing(1);//底部添加关闭connect(closeButton, &QPushButton::clicked, [=]() {this->hide();emit closeSig();});this->setWindowFlags(this->windowFlags() | Qt::WindowCloseButtonHint);this->setStyleSheet("background-color: rgb(19, 46, 74);");
}StatisticChartsWindow::~StatisticChartsWindow()
{if(chart1) {delete  chart1;}if(chart2) {delete  chart2;}
}void StatisticChartsWindow::createPie1(QMap<QString, int> data, QString title)
{// 创建一个饼图系列series1->clear();int count=0; //计算总数QMap<int, QList<QString>> map;for(auto it=data.begin(); it!=data.end(); it++) {count += it.value();}QList<QMap<QString, int>> sortList = getsortListByValue(data);// 根据条数比例排序,从大到小for(QMap<QString, int> map: sortList) {QString keyLable = map.firstKey();int num = map.value(keyLable);double ratio = num/1.0/count*100;QString ratioStr = QString::number(ratio, 'f', 1);QString lable = QString("%1,条数:%2,占比,%3%").arg(keyLable).arg(num).arg(ratioStr);appendSlice1(lable, num); // 添加到饼图中}// 创建一个新的图表并添加系列chart1->setTitle(title);//chart1->removeAllSeries();chart1->addSeries(series1);
}void StatisticChartsWindow::createPie2(QMap<QString, int> data, QString title)
{// 创建一个饼图系列series2->clear();int count=0; //计算总数QMap<int, QList<QString>> map;for(auto it=data.begin(); it!=data.end(); it++) {count += it.value();}QList<QMap<QString, int>> sortList = getsortListByValue(data);for(QMap<QString, int> map: sortList) {QString keyLable = map.firstKey();int num = map.value(keyLable);double ratio = num/1.0/count*100;QString ratioStr = QString::number(ratio, 'f', 1);QString lable = QString("%1,条数:%2,占比,%3%").arg(keyLable).arg(num).arg(ratioStr);appendSlice2(lable, num);}// 创建一个新的图表并添加系列chart2->setTitle(title);//chart2->removeAllSeries();chart2->addSeries(series2);
}void StatisticChartsWindow::appendSlice1(QString lable, int value)
{CustomSlice *customSlice = new  CustomSlice(lable, value);customSlice->setBrush(QBrush(getRandomColor())); //设置填充颜色//customSlice->setPen(QPen(Qt::black)); //设置线条颜色CustomSlice1List.append(customSlice);*series1 << customSlice;
}void StatisticChartsWindow::appendSlice2(QString lable, int value)
{CustomSlice *customSlice = new  CustomSlice(lable, value);customSlice->setBrush(QBrush(getRandomColor())); //设置填充颜色CustomSlice2List.append(customSlice);*series2 << customSlice;}void StatisticChartsWindow::removeAllSlice()
{for(CustomSlice* custom: CustomSlice1List) {series1->remove(custom);}for(CustomSlice* custom: CustomSlice2List) {series2->remove(custom);}qDeleteAll(CustomSlice1List);qDeleteAll(CustomSlice2List);CustomSlice1List.clear();CustomSlice2List.clear();
}Qt::GlobalColor StatisticChartsWindow::getRandomColor()
{int randomValue = QRandomGenerator::global()->bounded(0, colorList.size()-1);return colorList.takeAt(randomValue);
}QList<QMap<QString, int>> StatisticChartsWindow::getsortListByValue(QMap<QString, int> &data)
{QList<QMap<QString, int>> sortList;QList<int> valueList;for(auto it=data.begin(); it!=data.end(); it++) {if(!valueList.contains(it.value())) {valueList.append(it.value());}}//根据值逆序排序std::sort(valueList.begin(), valueList.end(), std::greater<int>());for(int value: valueList) {for(QString key: data.keys(value)) {QMap<QString, int> map;map.insert(key, value);sortList.append(map);}}return sortList;
}

我的这个例子是,点击统计按钮之后,获取相应的数据,然后生成相应的饼图

    QObject::connect(ui.statisticsBtn, &QPushButton::clicked, [=]() {g_dataCache->setSystemLog(SC3C::eSystemLogType::QUERY_SYSTEMLOG, QString("成功"),"查看日志统计");StatisticChartsWindow window;if(StatisticWindow) {tableView->hide();StatisticWindow->show();return;}StatisticWindow = new StatisticChartsWindow(q);QObject::connect(StatisticWindow, &StatisticChartsWindow::closeSig, q, [=]() {tableView->show();});//  标签名,  数量QMap<QString, int> map1 = { };QMap<QString, int> map2 = { };int logType = ui.logType->currentData().toInt();int eventType = ui.eventType->currentData().toInt();QString Name = ui.operatorName->currentText();tableModel.second->setFilterOperator("所有");// 获取数据,map1表示饼图一需要的数据getEventTypeStatisticHash(map1, map2);//恢复之前显示的tableModel.second->setFilterType(logType, eventType);tableModel.second->setFilterOperator(Name);//SC3C::Valwell::Widget::setBackgroundCommon2WithMargins(window);StatisticWindow->setFixedSize(q->size());//StatisticWindow->setStyleSheet("background-color: transparent;");StatisticWindow->createPie1(map1, "事件类型统计");StatisticWindow->createPie2(map2, "日志类型统计");StatisticWindow->show();tableView->hide();});

只需要把map放入创建饼图的函数即可,map中对应的是QMap<标签名,数量>,也就是饼图右侧的标签

        StatisticWindow->createPie1(map1, "事件类型统计");StatisticWindow->createPie2(map2, "日志类型统计");

这样就可以出饼图了

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/120902.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux系统编程(1)

父子进程通过两个管道进行通信。 伪代码 #include <unistd.h> void client(int, int), server(int, int);int main(int argc, char** argv) {int pipe1[2], pipe2[2];pid_t childpid;Pipe(pipe1);Pipe(pipe2);if ((childpid Fork()) 0) {// childClose(pipe1[1]);Close…

上网Tips: Linux截取动态效果图工具_byzanz

链接1 链接2 安装&#xff1a; sudo apt-get install byzanz 查看指令 说明 byzanz-record --help日常操作 xwininfo点击 待录制窗口 左上角 byzanz-record -x 72 -y 64 -w 1848 -h 893 -d 10 --delay5 -c /home/xixi/myGIF/test.gif小工具 获取鼠标坐标 xdotool getm…

python使用mitmproxy和mitmdump抓包之拦截和修改包(四)

我认为mitmproxy最强大的地方&#xff0c;就是mitmdump可以结合python代码&#xff0c;灵活拦截和处理数据包。 首先&#xff0c;mitmdump的路径如下&#xff1a;&#xff08;使用pip3 install mitmproxy安装的情况&#xff0c;参考我的文章python使用mitmproxy和mitmdump抓包…

Django(21):使用Celery任务框架

目录 Celery介绍Celery安装Celery使用项目文件和配置启动Celery编写任务调用异步任务查看任务执行状态及结果 设置定时和周期性任务配置文件添加任务Django Admin添加周期性任务启动任务调度器beat Flower监控任务执行状态Celery高级用法与注意事项给任务设置最大重试次数不同任…

【Orange Pi】Orange Pi5 Plus 安装记录

官网&#xff1a;Orange Pi - Orangepi 主控芯片&#xff1a;Rockchip RK3588(8nm LP制程&#xff09;NPU&#xff1a;内嵌的 NPU 支持INT4/INT8/INT16/FP16混合运算&#xff0c;算力高达 6Top支持的操作系统&#xff1a; Orangepi OS&#xff08;Droid&#xff09;Orangepi O…

lwIP 开发指南(下)

目录 NETCONN 编程接口简介netbuf 数据缓冲区netconn 连接结构netconn 编程API 函数 NETCONN 编程接口UDP 实验NETCONN 实现UDPNETCONN 接口的UDP 实验硬件设计软件设计下载验证 NETCONN 接口编程TCP 客户端实验NETCONN 实现TCP 客户端连接步骤NETCONN 接口的TCPClient 实验硬件…

华为智能企业远程办公安全解决方案(1)

华为智能企业远程办公安全解决方案&#xff08;1&#xff09; 课程地址方案背景需求分析企业远程办公业务概述企业远程办公安全风险分析企业远程办公环境搭建需求分析 方案设计组网架构设备选型方案亮点 课程地址 本方案相关课程资源已在华为O3社区发布&#xff0c;可按照以下…

Vue组件通信方式

1.props通信 1.1在 Vue 2 中使用 props 通信 注意:props传递的数据是只读的,子组件修改,不会影响父组件 1.1.1.定义 props 在子组件中使用 props 选项来定义要接收的属性 // 子组件 <script> export default {props: {message: String} } </script>1.1.2.传递…

预编译(1)

目录 预定义符号&#xff1a; 使用&#xff1a; 结果&#xff1a; 预编译前后对比&#xff1a; #define定义常量&#xff1a; 基本语法&#xff1a; 举例1&#xff1a; 结果&#xff1a; 预编译前后对比&#xff1a; 举例2&#xff1a; 预编译前后对比&#xff1a; 注…

Lua表公共操作

--表的公共操作 t1 {{age 1,name "123"},{age 2,name "456"}} t2 {name "Holens" , sex true} --插入 print(#t1) table.insert(t1,t2) print(#t1) print(t1[3].sex) print("*************************************")--删除 -…

wordpress插件-免费的wordpress全套插件

在当今数字化时代&#xff0c;网站和博客已经成为信息传递、观点分享和商业交流的重要平台。在这个背景下&#xff0c;WordPress作为最受欢迎的内容管理系统之一&#xff0c;无疑扮演着至关重要的角色。然而&#xff0c;要保持一个成功的WordPress网站&#xff0c;不仅需要出色…

关于操作系统与内核科普

关于操作系统与内核科普 一.什么是操作系统 操作系统是管理计算机硬件与软件资源的计算机程序。它为计算机硬件和软件提供了一种中间层。 操作系统是一种软件&#xff0c;主要目的有三种&#xff1a; 一.管理计算机资源&#xff0c;这些资源包括CPU&#xff0c;内存&#xff0…