#include "coalstatisticschartwidget.h" #include "ui_coalstatisticschartwidget.h" CoalStatisticsChartWidget::CoalStatisticsChartWidget(QWidget* parent) : QWidget(parent) , ui(new Ui::CoalStatisticsChartWidget) { ui->setupUi(this); initCoalStatisticsBarChart(); } CoalStatisticsChartWidget::~CoalStatisticsChartWidget() { delete ui; } void CoalStatisticsChartWidget::initCoalStatisticsBarChart() { // 创建图表 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); // 设置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); 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); // 获取 widget_coalChart 的布局 QVBoxLayout* layout = static_cast(ui->widget_coalChart->layout()); if (!layout) { // 如果没有布局,创建一个新的布局并设置 layout = new QVBoxLayout(ui->widget_coalChart); ui->widget_coalChart->setLayout(layout); } // 设置布局参数 layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); // 确保视图只添加一次 if (!layout->indexOf(m_chartView) != -1) { layout->addWidget(m_chartView); } }