#include "coaldistributbarchartwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include CoalDistributBarChartWidget::CoalDistributBarChartWidget(QWidget* parent) : QWidget(parent) { initializeChart(); // setupTimer(); } void CoalDistributBarChartWidget::updateChart() { double newValue = QRandomGenerator::global()->bounded(0, 99); // 随机生成0-900的Y值 // 更新当前柱子的值 QBarSet* currentBarSet = static_cast(m_series->barSets().at(currentIndex)); currentBarSet->replace(0, newValue); // 更新当前柱子的值 // 循环更新下一个柱子的索引 currentIndex = (currentIndex + 1) % m_series->count(); // 循环到下一个柱子 } void CoalDistributBarChartWidget::initializeChart() { // 创建图标 m_chart = new QChart(); m_chart->setBackgroundBrush(Qt::transparent); m_chart->setMargins(QMargins(0, 0, 0, 0)); // 创建窗口并设置图表 m_chartView = new QChartView(m_chart); m_chartView->setBackgroundBrush(Qt::transparent); m_chartView->setStyleSheet("background: transparent;"); // 使用样式表确保透明 m_chartView->setRenderHint(QPainter::Antialiasing); m_chartView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // 创建柱状图 m_series = new QBarSeries(); m_chart->addSeries(m_series); // 创建300个柱状集 // for (int i = 0; i < 300; ++i) { // QBarSet* barSet = new QBarSet(QString::number(i)); // 使用柱子编号作为名称 // barSet->append(0); // 初始化值为0 // m_series->append(barSet); // } // 设置X轴为时间 QValueAxis* axisX = new QValueAxis; axisX->setRange(1, 300); axisX->setTickCount(10); axisX->setLabelFormat("%d"); axisX->setLinePen(QPen(Qt::gray)); axisX->setLabelsColor(Qt::gray); axisX->setMinorTickCount(0); // 隐藏X轴刻度线 m_chart->addAxis(axisX, Qt::AlignBottom); m_series->attachAxis(axisX); // 设置Y轴为百分比 QValueAxis* axisY = new QValueAxis; axisY->setTitleText("占比(%)"); axisY->setTitleBrush(QBrush(Qt::gray)); axisY->setLinePen(QPen(Qt::gray)); axisY->setLabelsColor(Qt::gray); // 设置标签字体颜色为灰色 axisY->setRange(0, 100); m_chart->addAxis(axisY, Qt::AlignLeft); m_series->attachAxis(axisY); // 设置Y轴标题位置 axisY->setTitleFont(QFont("Arial", 10)); // 设置标题字体 axisY->setTitleVisible(true); // 确保标题可见 QVBoxLayout* layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); // 设置间距为0 layout->addWidget(m_chartView); setLayout(layout); } void CoalDistributBarChartWidget::setupTimer() { // 定时器设置 m_timer = new QTimer(this); connect(m_timer, &QTimer::timeout, this, &CoalDistributBarChartWidget::updateChart); m_timer->start(1000); // 每秒更新一次 }