87 lines
2.4 KiB
C++
87 lines
2.4 KiB
C++
#include "coaldistributchartwidget.h"
|
|
#include "ui_coaldistributchartwidget.h"
|
|
|
|
#include <QVBoxLayout>
|
|
|
|
CoalDistributChartWidget::CoalDistributChartWidget(QWidget *parent)
|
|
: QWidget(parent), ui(new Ui::CoalDistributChartWidget) {
|
|
|
|
initializeChart(); // 初始化图表
|
|
initializeTimeAxis(); // 初始化时间轴
|
|
|
|
// 设置定时器
|
|
m_timer = new QTimer(this);
|
|
connect(m_timer, &QTimer::timeout, this,
|
|
&CoalDistributChartWidget::updateChart);
|
|
|
|
ui->setupUi(this);
|
|
m_timer->start(1000); // 每秒更新一次
|
|
}
|
|
|
|
CoalDistributChartWidget::~CoalDistributChartWidget() { delete ui; }
|
|
|
|
void CoalDistributChartWidget::updateChart() {
|
|
updateBarData();
|
|
updateTimeAxis();
|
|
}
|
|
|
|
void CoalDistributChartWidget::initializeChart() {
|
|
m_chart = new QChart(); // 将chart设为类成员
|
|
m_series = new QBarSeries();
|
|
|
|
// 创建柱状图数据
|
|
m_barSet = new QBarSet("数据1");
|
|
m_series->append(m_barSet);
|
|
m_chart->addSeries(m_series);
|
|
|
|
// 设置X轴为时间
|
|
m_axisX = new QCategoryAxis();
|
|
m_chart->addAxis(m_axisX, Qt::AlignBottom);
|
|
m_series->attachAxis(m_axisX);
|
|
|
|
// 设置Y轴为百分比
|
|
m_axisY = new QValueAxis();
|
|
m_axisY->setRange(0, 100); // 设置范围为0到100%
|
|
m_chart->addAxis(m_axisY, Qt::AlignLeft);
|
|
m_series->attachAxis(m_axisY);
|
|
|
|
m_chart->setTitle("动态柱状图示例");
|
|
|
|
auto *chartView = new QChartView(m_chart);
|
|
chartView->setRenderHint(QPainter::Antialiasing);
|
|
|
|
// 清空之前的布局,避免重复添加
|
|
QLayout *currentLayout = this->layout();
|
|
if (currentLayout) {
|
|
QLayoutItem *item;
|
|
while ((item = currentLayout->takeAt(0))) {
|
|
delete item->widget(); // 删除现有的widget
|
|
delete item; // 删除布局项
|
|
}
|
|
}
|
|
|
|
// 创建新的布局
|
|
QVBoxLayout *newLayout = new QVBoxLayout(this); // 使用不同的变量名
|
|
newLayout->addWidget(chartView);
|
|
setLayout(newLayout);
|
|
}
|
|
|
|
void CoalDistributChartWidget::initializeTimeAxis() {
|
|
for (int i = 0; i < 5; ++i) {
|
|
m_axisX->append(
|
|
QDateTime::currentDateTime().addSecs(i).toString("HH:mm:ss"), i);
|
|
}
|
|
}
|
|
|
|
void CoalDistributChartWidget::updateBarData() {
|
|
// 更新柱状图数据
|
|
*m_barSet << qrand() % 101; // 随机生成0到100之间的值
|
|
}
|
|
|
|
void CoalDistributChartWidget::updateTimeAxis() {
|
|
// 更新时间轴
|
|
m_axisX->remove(0); // 移除第一个时间
|
|
m_axisX->append(QDateTime::currentDateTime().toString("HH:mm:ss"),
|
|
4); // 添加新的时间
|
|
}
|