feat:qcutsomplots

This commit is contained in:
“Diviner66”, 2024-11-11 22:19:24 +08:00
parent c76b687c2a
commit 47793afcca
8 changed files with 44130 additions and 686 deletions

View File

@ -7,6 +7,8 @@
QT += core gui QT += core gui
QT += charts QT += charts
QT += network QT += network
QT += printsupport
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = HX_CoalFlowDetect TARGET = HX_CoalFlowDetect
@ -26,6 +28,7 @@ DEFINES += QT_DEPRECATED_WARNINGS
CONFIG += c++11 CONFIG += c++11
SOURCES += \ SOURCES += \
component/qcustomplot/qcustomplot.cpp \
controller/coaldistributmodbusthread.cpp \ controller/coaldistributmodbusthread.cpp \
main.cpp \ main.cpp \
mainwindow.cpp \ mainwindow.cpp \
@ -38,6 +41,7 @@ SOURCES += \
component/ZDateEdit/ztimeedit.cpp\ component/ZDateEdit/ztimeedit.cpp\
HEADERS += \ HEADERS += \
component/qcustomplot/qcustomplot.h \
controller/coaldistributmodbusthread.h \ controller/coaldistributmodbusthread.h \
mainwindow.h \ mainwindow.h \
view/beltspeedlinewidget.h \ view/beltspeedlinewidget.h \

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -7,180 +7,212 @@
#include <QDateTime> #include <QDateTime>
#include <QTimer> #include <QTimer>
MainWindow::MainWindow(QWidget* parent) MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
, ui(new Ui::MainWindow) ui->setupUi(this);
{ this->setWindowFlag(Qt::FramelessWindowHint);
ui->setupUi(this); this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint |
this->setWindowFlag(Qt::FramelessWindowHint); Qt::WindowMinimizeButtonHint);
this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint);
ui->widget_head->installEventFilter(this); ui->widget_head->installEventFilter(this);
m_systemSetting = new QSettings("system.ini", QSettings::IniFormat); m_systemSetting = new QSettings("system.ini", QSettings::IniFormat);
this->setWindowTitle(m_systemSetting->value("system/name").toString()); createSystemINI();
calendarLoopPlay(); this->setWindowTitle(m_systemSetting->value("system/name").toString());
setSystemTitle(); calendarLoopPlay();
setBeltWarnInfoTextEditStyle(); setSystemTitle();
addcoalDistributChart(); setBeltWarnInfoTextEditStyle();
addbeltSpeedChat(); addcoalDistributChart();
addCoalStatisticsChart(); addbeltSpeedChat();
addCoalBeltVideo(); addCoalStatisticsChart();
addCoalBeltVideo();
} }
MainWindow::~MainWindow() { delete ui; } MainWindow::~MainWindow() { delete ui; }
bool MainWindow::eventFilter(QObject* watched, QEvent* event) bool MainWindow::eventFilter(QObject *watched, QEvent *event) {
{ // 处理鼠标按下、释放和移动事件
// 处理鼠标按下、释放和移动事件 if (watched == ui->widget_head) {
if (watched == ui->widget_head) { QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event); if (mouseEvent->type() == QEvent::MouseButtonPress) {
if (mouseEvent->type() == QEvent::MouseButtonPress) { if (mouseEvent->button() == Qt::LeftButton) {
if (mouseEvent->button() == Qt::LeftButton) { m_mousePressed = true; // 启动拖拽
m_mousePressed = true; // 启动拖拽 m_mousePoint = mouseEvent->globalPos() - this->pos();
m_mousePoint = mouseEvent->globalPos() - this->pos();
this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint | Qt::Window | Qt::WindowStaysOnTopHint); this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint |
this->show(); // 确保窗口显示 Qt::WindowMinimizeButtonHint | Qt::Window |
Qt::WindowStaysOnTopHint);
this->show(); // 确保窗口显示
return true; return true;
} }
} else if (mouseEvent->type() == QEvent::MouseButtonRelease) { } else if (mouseEvent->type() == QEvent::MouseButtonRelease) {
m_mousePressed = false; m_mousePressed = false;
return true; return true;
} else if (mouseEvent->type() == QEvent::MouseMove) { } else if (mouseEvent->type() == QEvent::MouseMove) {
if (m_mousePressed && (mouseEvent->buttons() & Qt::LeftButton)) { if (m_mousePressed && (mouseEvent->buttons() & Qt::LeftButton)) {
this->move(mouseEvent->globalPos() - m_mousePoint); this->move(mouseEvent->globalPos() - m_mousePoint);
// 每次移动时设置为最上方 // 每次移动时设置为最上方
this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint | Qt::Window | Qt::WindowStaysOnTopHint); this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint |
this->show(); Qt::WindowMinimizeButtonHint | Qt::Window |
return true; Qt::WindowStaysOnTopHint);
} this->show();
} return true;
}
} }
}
} }
void MainWindow::addBeltWarnInfoToTextEdit(const QString& consoleInfo) void MainWindow::addBeltWarnInfoToTextEdit(const QString &consoleInfo) {
{ qDebug() << consoleInfo;
qDebug() << consoleInfo; m_textEditConsoleInfo.append(consoleInfo);
m_textEditConsoleInfo.append(consoleInfo); QDateTime startDateTime = QDateTime::currentDateTime();
QDateTime startDateTime = QDateTime::currentDateTime(); QString formattedTime = startDateTime.toString("yyyy-MM-dd hh:mm:ss");
QString formattedTime = startDateTime.toString("yyyy-MM-dd hh:mm:ss");
if (m_textEditConsoleInfo.isEmpty()) if (m_textEditConsoleInfo.isEmpty())
return; return;
QString lastConsoleInfo = m_textEditConsoleInfo.last(); QString lastConsoleInfo = m_textEditConsoleInfo.last();
// qint64 timeDifferenceInMilliseconds = m_previousConsleInfoDateTime.secsTo(startDateTime); // qint64 timeDifferenceInMilliseconds =
// m_previousConsleInfoDateTime.secsTo(startDateTime);
// if ((lastConsoleInfo == consoleInfo) && timeDifferenceInMilliseconds < 2) // if ((lastConsoleInfo == consoleInfo) && timeDifferenceInMilliseconds <
// return; // 2)
// return;
QString consoleInfoResult = QStringLiteral("[%1]%2").arg(formattedTime).arg(consoleInfo); QString consoleInfoResult =
ui->textEdit_beltWarnInfo->append(consoleInfoResult); QStringLiteral("[%1]%2").arg(formattedTime).arg(consoleInfo);
ui->textEdit_beltWarnInfo->append(consoleInfoResult);
m_previousConsleInfoDateTime = QDateTime::currentDateTime(); m_previousConsleInfoDateTime = QDateTime::currentDateTime();
} }
void MainWindow::on_pushButton_close_clicked() { this->close(); } void MainWindow::on_pushButton_close_clicked() { this->close(); }
void MainWindow::on_pushButton_max_clicked() void MainWindow::on_pushButton_max_clicked() {
{ if (isFullScreen()) {
if (isFullScreen()) { this->showMaximized();
this->showMaximized(); } else {
} else { this->showFullScreen();
this->showFullScreen(); }
}
} }
void MainWindow::on_pushButton_min_clicked() { this->showMinimized(); } void MainWindow::on_pushButton_min_clicked() { this->showMinimized(); }
void MainWindow::calendarLoopPlay() void MainWindow::calendarLoopPlay() {
{ ui->label_calendar->clear();
ui->label_calendar->clear(); QTimer *timer_calendar = new QTimer(this);
QTimer* timer_calendar = new QTimer(this); connect(timer_calendar, &QTimer::timeout, this, [this]() {
connect(timer_calendar, &QTimer::timeout, this, [this]() { QDateTime time = QDateTime::currentDateTime();
QDateTime time = QDateTime::currentDateTime(); QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd"); ui->label_calendar->setText(str);
ui->label_calendar->setText(str); });
}); timer_calendar->start(1000); //每一秒溢出一次进入槽函数
timer_calendar->start(1000); //每一秒溢出一次进入槽函数
} }
void MainWindow::setSystemTitle() void MainWindow::createSystemINI() {
{ // 写入数据到INI文件
QString titleName = m_systemSetting->value("system/name").toString(); // 判断并设置 "system/name"
if (!titleName.isEmpty()) { if (!m_systemSetting->contains("system/name")) {
ui->label_title->clear(); m_systemSetting->setValue("system/name", "煤流监测平台");
ui->label_title->setText(titleName); }
}
// 判断并设置 "coalStaticInterface/url"
if (!m_systemSetting->contains("coalStaticInterface/url")) {
m_systemSetting->setValue("coalStaticInterface/url", 30);
}
// 判断并设置 "addr/ip"
if (!m_systemSetting->contains("addr/ip")) {
m_systemSetting->setValue("addr/ip", "127.0.0.1");
}
// 判断并设置 "addr/port"
if (!m_systemSetting->contains("addr/port")) {
m_systemSetting->setValue("addr/port", 3000);
}
// 判断并设置 "camera/rtsp"
if (!m_systemSetting->contains("camera/rtsp")) {
m_systemSetting->setValue("camera/rtsp", 3000);
}
} }
void MainWindow::setBeltWarnInfoTextEditStyle() void MainWindow::setSystemTitle() {
{ QString titleName = m_systemSetting->value("system/name").toString();
ui->textEdit_beltWarnInfo->document()->setMaximumBlockCount(100); if (!titleName.isEmpty()) {
ui->textEdit_beltWarnInfo->setReadOnly(true); ui->label_title->clear();
ui->textEdit_beltWarnInfo->setTextInteractionFlags(Qt::NoTextInteraction); ui->label_title->setText(titleName);
}
} }
void MainWindow::addcoalDistributChart() void MainWindow::setBeltWarnInfoTextEditStyle() {
{ ui->textEdit_beltWarnInfo->document()->setMaximumBlockCount(100);
// addBeltWarnInfoToTextEdit("添加煤流分布窗口成功!"); ui->textEdit_beltWarnInfo->setReadOnly(true);
ui->textEdit_beltWarnInfo->append("添加煤流分布窗口成功!"); ui->textEdit_beltWarnInfo->setTextInteractionFlags(Qt::NoTextInteraction);
CoalDistributBarChartWidget* coalDistributBarChartWidget = new CoalDistributBarChartWidget(this);
// 检查布局是否已设置
if (!ui->widget_coalDistributChart->layout()) {
ui->widget_coalDistributChart->setLayout(new QVBoxLayout);
}
coalDistributBarChartWidget->setContentsMargins(0, 0, 0, 0);
ui->widget_coalDistributChart->layout()->addWidget(
coalDistributBarChartWidget);
} }
void MainWindow::addbeltSpeedChat() void MainWindow::addcoalDistributChart() {
{ // addBeltWarnInfoToTextEdit("添加煤流分布窗口成功!");
ui->textEdit_beltWarnInfo->append("添加皮带机速度曲线窗口成功!"); ui->textEdit_beltWarnInfo->append("添加煤流分布窗口成功!");
BeltSpeedLineWidget* beltSpeedLineWidget = new BeltSpeedLineWidget(this);
// 检查布局是否已设置 CoalDistributBarChartWidget *coalDistributBarChartWidget =
if (!ui->widget_beltSpeedChart->layout()) { new CoalDistributBarChartWidget(this);
ui->widget_beltSpeedChart->setLayout(new QVBoxLayout);
} // 检查布局是否已设置
beltSpeedLineWidget->setContentsMargins(0, 0, 0, 0); if (!ui->widget_coalDistributChart->layout()) {
ui->widget_beltSpeedChart->layout()->addWidget(beltSpeedLineWidget); ui->widget_coalDistributChart->setLayout(new QVBoxLayout);
}
coalDistributBarChartWidget->setContentsMargins(0, 0, 0, 0);
ui->widget_coalDistributChart->layout()->addWidget(
coalDistributBarChartWidget);
} }
void MainWindow::addCoalStatisticsChart() void MainWindow::addbeltSpeedChat() {
{ ui->textEdit_beltWarnInfo->append("添加皮带机速度曲线窗口成功!");
ui->textEdit_beltWarnInfo->append("添加煤量统计窗口成功!"); BeltSpeedLineWidget *beltSpeedLineWidget = new BeltSpeedLineWidget(this);
CoalStatisticsChartWidget* coalStatisticsChartWidget = new CoalStatisticsChartWidget(this); // 检查布局是否已设置
// 检查布局是否已设置 if (!ui->widget_beltSpeedChart->layout()) {
if (!ui->widget_beltSpeedChart->layout()) { ui->widget_beltSpeedChart->setLayout(new QVBoxLayout);
ui->widget_beltSpeedChart->setLayout(new QVBoxLayout); }
} beltSpeedLineWidget->setContentsMargins(0, 0, 0, 0);
coalStatisticsChartWidget->setContentsMargins(0, 0, 0, 0); ui->widget_beltSpeedChart->layout()->addWidget(beltSpeedLineWidget);
ui->widget_coalStatisticsChart->layout()->addWidget(
coalStatisticsChartWidget);
connect(coalStatisticsChartWidget, &CoalStatisticsChartWidget::querySuccessInfo, this, &MainWindow::addBeltWarnInfoToTextEdit);
} }
void MainWindow::addCoalBeltVideo() void MainWindow::addCoalStatisticsChart() {
{ ui->textEdit_beltWarnInfo->append("添加煤量统计窗口成功!");
// QString url = "https://stream7.iqilu.com/10339/upload_transcode/202002/18/" CoalStatisticsChartWidget *coalStatisticsChartWidget =
// "20200218114723HDu3hhxqIT.mp4"; new CoalStatisticsChartWidget(this);
// QString url = "rtsp://admin:1234qwer@192.168.80.82:554/Streaming/Channels/101"; // 检查布局是否已设置
QString url = m_systemSetting->value("camera/rtsp").toString(); if (!ui->widget_beltSpeedChart->layout()) {
ui->widget_beltVideo->setUrl(url); ui->widget_beltSpeedChart->setLayout(new QVBoxLayout);
ui->widget_beltVideo->open(); }
coalStatisticsChartWidget->setContentsMargins(0, 0, 0, 0);
ui->widget_coalStatisticsChart->layout()->addWidget(
coalStatisticsChartWidget);
connect(coalStatisticsChartWidget,
&CoalStatisticsChartWidget::querySuccessInfo, this,
&MainWindow::addBeltWarnInfoToTextEdit);
}
void MainWindow::addCoalBeltVideo() {
// QString url =
// "https://stream7.iqilu.com/10339/upload_transcode/202002/18/"
// "20200218114723HDu3hhxqIT.mp4";
// QString url =
// "rtsp://admin:1234qwer@192.168.80.82:554/Streaming/Channels/101";
QString url = m_systemSetting->value("camera/rtsp").toString();
ui->widget_beltVideo->setUrl(url);
ui->widget_beltVideo->open();
} }

View File

@ -10,86 +10,91 @@ class MainWindow;
} }
class MainWindow : public QMainWindow { class MainWindow : public QMainWindow {
Q_OBJECT Q_OBJECT
public: public:
explicit MainWindow(QWidget* parent = nullptr); explicit MainWindow(QWidget *parent = nullptr);
~MainWindow(); ~MainWindow();
protected: protected:
bool eventFilter(QObject* watched, QEvent* event) override; bool eventFilter(QObject *watched, QEvent *event) override;
public slots: public slots:
/** /**
* @brief * @brief
* @param consoleInfo * @param consoleInfo
*/ */
void addBeltWarnInfoToTextEdit(const QString& consoleInfo); void addBeltWarnInfoToTextEdit(const QString &consoleInfo);
private slots: private slots:
void on_pushButton_close_clicked(); void on_pushButton_close_clicked();
void on_pushButton_max_clicked(); void on_pushButton_max_clicked();
void on_pushButton_min_clicked(); void on_pushButton_min_clicked();
private: private:
/** /**
* @brief calendarLoopPlay * @brief calendarLoopPlay
*/ */
void calendarLoopPlay(); void calendarLoopPlay();
/** /**
* @brief setSystemTitle * @brief createSystemINI
*/ */
void setSystemTitle(); void createSystemINI();
/** /**
* @brief setSystemTitle
*/
void setSystemTitle();
/**
* @brief setBeltWarnInfoTextEditStyle * @brief setBeltWarnInfoTextEditStyle
*/ */
void setBeltWarnInfoTextEditStyle(); void setBeltWarnInfoTextEditStyle();
/** /**
* @brief addcoalDistributChart * @brief addcoalDistributChart
*/ */
void addcoalDistributChart(); void addcoalDistributChart();
/** /**
* @brief addbeltSpeedChat 线 * @brief addbeltSpeedChat 线
*/ */
void addbeltSpeedChat(); void addbeltSpeedChat();
/** /**
* @brief addCoalStatisticsChart * @brief addCoalStatisticsChart
*/ */
void addCoalStatisticsChart(); void addCoalStatisticsChart();
/** /**
* @brief addCoalBeltVideo * @brief addCoalBeltVideo
*/ */
void addCoalBeltVideo(); void addCoalBeltVideo();
private: private:
Ui::MainWindow* ui; Ui::MainWindow *ui;
/** /**
* @brief m_textEditConsoleInfo * @brief m_textEditConsoleInfo
*/ */
QList<QString> m_textEditConsoleInfo; QList<QString> m_textEditConsoleInfo;
/** /**
* @brief m_previousConsleInfoDateTime * @brief m_previousConsleInfoDateTime
*/ */
QDateTime m_previousConsleInfoDateTime; QDateTime m_previousConsleInfoDateTime;
/** /**
* @brief m_systemSetting * @brief m_systemSetting
*/ */
QSettings* m_systemSetting; QSettings *m_systemSetting;
// 窗口拖拽 // 窗口拖拽
QPoint m_mousePoint; QPoint m_mousePoint;
bool m_mousePressed { false }; bool m_mousePressed{false};
}; };
#endif // MAINWINDOW_H #endif // MAINWINDOW_H

View File

@ -19,230 +19,221 @@
#include <memory> #include <memory>
CoalDistributBarChartWidget::CoalDistributBarChartWidget(QWidget* parent) CoalDistributBarChartWidget::CoalDistributBarChartWidget(QWidget *parent)
: QWidget(parent) : QWidget(parent), m_tcpSocket(new QTcpSocket(this)) {
, m_tcpSocket(new QTcpSocket(this)) initializeChart();
{
initializeChart();
m_systemSetting = new QSettings("system.ini", QSettings::IniFormat); m_systemSetting = new QSettings("system.ini", QSettings::IniFormat);
connectTCPSocket(); // connectTCPSocket();
setupTimer(); // setupTimer();
} }
CoalDistributBarChartWidget::~CoalDistributBarChartWidget() CoalDistributBarChartWidget::~CoalDistributBarChartWidget() {
{ if (m_tcpSocket->state() == QAbstractSocket::ConnectedState) {
if (m_tcpSocket->state() == QAbstractSocket::ConnectedState) { m_tcpSocket->disconnectFromHost();
m_tcpSocket->disconnectFromHost(); m_tcpSocket->waitForDisconnected();
m_tcpSocket->waitForDisconnected(); }
} delete m_tcpSocket;
delete m_tcpSocket;
} }
void CoalDistributBarChartWidget::updateChart() void CoalDistributBarChartWidget::updateChart() {
{ int radio = getCoalRatioByTCPSocket();
int radio = getCoalRatioByTCPSocket(); if (radio < 0 || radio > 90) {
if (radio < 0 || radio > 90) { return;
return; }
}
int setCount = m_set->count(); int setCount = m_set->count();
m_set->remove(setCount - 1); m_set->remove(setCount - 1);
m_set->insert(0, radio); m_set->insert(0, radio);
} }
void CoalDistributBarChartWidget::initializeChart() void CoalDistributBarChartWidget::initializeChart() {
{ // 创建图标
// 创建图标 m_chart = new QChart();
m_chart = new QChart();
m_chart->setBackgroundBrush(Qt::transparent); m_chart->setBackgroundBrush(Qt::transparent);
m_chart->setMargins(QMargins(0, 0, 0, 0)); m_chart->setMargins(QMargins(0, 0, 0, 0));
m_chart->legend()->hide(); m_chart->legend()->hide();
// 创建窗口并设置图表 // 创建窗口并设置图表
m_chartView = new QChartView(m_chart); m_chartView = new QChartView(m_chart);
m_chartView->setBackgroundBrush(Qt::transparent); m_chartView->setBackgroundBrush(Qt::transparent);
m_chartView->setStyleSheet("background: transparent;"); // 使用样式表确保透明 m_chartView->setStyleSheet("background: transparent;"); // 使用样式表确保透明
m_chartView->setRenderHint(QPainter::Antialiasing); m_chartView->setRenderHint(QPainter::Antialiasing);
m_chartView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_chartView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// 创建柱状图 // 创建柱状图
m_series = new QBarSeries(); m_series = new QBarSeries();
m_chart->addSeries(m_series); m_chart->addSeries(m_series);
// 设置X轴为据煤溜摄像机距离 // 设置X轴为据煤溜摄像机距离
QValueAxis* axisX = new QValueAxis; QValueAxis *axisX = new QValueAxis;
axisX->setRange(1, 300); axisX->setRange(1, 300);
axisX->setTickCount(10); axisX->setTickCount(10);
axisX->setLabelFormat("%d"); axisX->setLabelFormat("%d");
axisX->setLinePen(QPen(Qt::gray)); axisX->setLinePen(QPen(Qt::gray));
axisX->setLabelsColor(Qt::gray); axisX->setLabelsColor(Qt::gray);
axisX->setMinorTickCount(0); // 隐藏X轴刻度线 axisX->setMinorTickCount(0); // 隐藏X轴刻度线
m_chart->addAxis(axisX, Qt::AlignBottom); m_chart->addAxis(axisX, Qt::AlignBottom);
m_series->attachAxis(axisX); m_series->attachAxis(axisX);
// 设置Y轴为百分比 // 设置Y轴为百分比
QValueAxis* axisY = new QValueAxis; QValueAxis *axisY = new QValueAxis;
axisY->setTitleText("占比(%)"); axisY->setTitleText("占比(%)");
axisY->setTitleBrush(QBrush(Qt::gray)); axisY->setTitleBrush(QBrush(Qt::gray));
axisY->setLinePen(QPen(Qt::gray)); axisY->setLinePen(QPen(Qt::gray));
axisY->setLabelsColor(Qt::gray); // 设置标签字体颜色为灰色 axisY->setLabelsColor(Qt::gray); // 设置标签字体颜色为灰色
axisY->setRange(0, 100); axisY->setRange(0, 100);
axisY->setTitleFont(QFont("Arial", 10)); // 设置标题字体 axisY->setTitleFont(QFont("Arial", 10)); // 设置标题字体
axisY->setTitleVisible(true); // 确保标题可见 axisY->setTitleVisible(true); // 确保标题可见
m_chart->addAxis(axisY, Qt::AlignLeft); m_chart->addAxis(axisY, Qt::AlignLeft);
m_series->attachAxis(axisY); m_series->attachAxis(axisY);
// 初始化默认数据集 // 初始化默认数据集
m_set = new QBarSet("测试1"); m_set = new QBarSet("测试1");
m_set->setColor(QColor(95, 180, 255)); m_set->setColor(QColor(95, 180, 255));
m_set->setBorderColor(QColor(95, 180, 255)); m_set->setBorderColor(QColor(95, 180, 255));
QRandomGenerator* generator = QRandomGenerator::global(); QRandomGenerator *generator = QRandomGenerator::global();
for (int i = 0; i < 300; i++) { for (int i = 0; i < 300; i++) {
int randomNumber = generator->bounded(10, 51); int randomNumber = generator->bounded(10, 51);
*m_set << randomNumber; *m_set << randomNumber;
} }
m_series->append(m_set); m_series->append(m_set);
QVBoxLayout* layout = new QVBoxLayout(this); QVBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0); layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0); // 设置间距为0 layout->setSpacing(0); // 设置间距为0
layout->addWidget(m_chartView); layout->addWidget(m_chartView);
setLayout(layout); setLayout(layout);
} }
void CoalDistributBarChartWidget::setupTimer() void CoalDistributBarChartWidget::setupTimer() {
{ // 定时器设置
// 定时器设置 m_timer = new QTimer(this);
m_timer = new QTimer(this); connect(m_timer, &QTimer::timeout, this,
connect(m_timer, &QTimer::timeout, this, &CoalDistributBarChartWidget::updateChart);
&CoalDistributBarChartWidget::updateChart); m_timer->start(1000); // 每秒更新一次
m_timer->start(1000); // 每秒更新一次
} }
void CoalDistributBarChartWidget::connectTCPSocket() void CoalDistributBarChartWidget::connectTCPSocket() {
{ QString ipAddress = m_systemSetting->value("addr/ip").toString();
QString ipAddress = m_systemSetting->value("addr/ip").toString(); quint16 port = m_systemSetting->value("addr/port").toInt();
quint16 port = m_systemSetting->value("addr/port").toInt();
// 连接到 Modbus TCP 服务器 // 连接到 Modbus TCP 服务器
m_tcpSocket->connectToHost(ipAddress, port); m_tcpSocket->connectToHost(ipAddress, port);
if (!m_tcpSocket->waitForConnected(5000)) { if (!m_tcpSocket->waitForConnected(5000)) {
qDebug() << "连接失败:" << m_tcpSocket->errorString(); qDebug() << "连接失败:" << m_tcpSocket->errorString();
} }
} }
int CoalDistributBarChartWidget::getCoalRatioByTCPSocket() int CoalDistributBarChartWidget::getCoalRatioByTCPSocket() {
{ if (m_tcpSocket->state() != QAbstractSocket::ConnectedState) {
if (m_tcpSocket->state() != QAbstractSocket::ConnectedState) { qDebug() << "未连接到服务器";
qDebug() << "未连接到服务器"; return -1; // 返回错误值
return -1; // 返回错误值 }
}
// 构建 Modbus 请求 // 构建 Modbus 请求
const quint8 unitId = 1; // 单元 ID const quint8 unitId = 1; // 单元 ID
const quint8 functionCode = 0x03; // 读保持寄存器 const quint8 functionCode = 0x03; // 读保持寄存器
const quint16 startAddress = 699; // 寄存器地址 const quint16 startAddress = 699; // 寄存器地址
const quint16 registerCount = 1; // 读取寄存器数量 const quint16 registerCount = 1; // 读取寄存器数量
// 构建请求数据 // 构建请求数据
QByteArray request; QByteArray request;
QDataStream stream(&request, QIODevice::WriteOnly); QDataStream stream(&request, QIODevice::WriteOnly);
stream.setByteOrder(QDataStream::BigEndian); // 使用大端字节序 stream.setByteOrder(QDataStream::BigEndian); // 使用大端字节序
// 添加 Modbus 请求报文各部分 // 添加 Modbus 请求报文各部分
stream << static_cast<quint16>(0x0004); // 事务 ID stream << static_cast<quint16>(0x0004); // 事务 ID
stream << static_cast<quint16>(0x0000); // 协议 ID stream << static_cast<quint16>(0x0000); // 协议 ID
stream << static_cast<quint16>(0x0006); // 剩余长度 stream << static_cast<quint16>(0x0006); // 剩余长度
stream << unitId; // 单元 ID stream << unitId; // 单元 ID
stream << functionCode; // 功能码 stream << functionCode; // 功能码
stream << static_cast<quint16>(startAddress); // 寄存器地址700 = 0x01BB stream << static_cast<quint16>(startAddress); // 寄存器地址700 = 0x01BB
stream << registerCount; // 寄存器数量 stream << registerCount; // 寄存器数量
// 发送请求 // 发送请求
m_tcpSocket->write(request); m_tcpSocket->write(request);
if (!m_tcpSocket->waitForBytesWritten(5000)) { if (!m_tcpSocket->waitForBytesWritten(5000)) {
qDebug() << "写入请求失败:" << m_tcpSocket->errorString(); qDebug() << "写入请求失败:" << m_tcpSocket->errorString();
return -1; // 返回错误值 return -1; // 返回错误值
} }
// 等待响应 // 等待响应
if (!m_tcpSocket->waitForReadyRead(5000)) { if (!m_tcpSocket->waitForReadyRead(5000)) {
qDebug() << "没有收到响应:" << m_tcpSocket->errorString(); qDebug() << "没有收到响应:" << m_tcpSocket->errorString();
return -1; // 返回错误值 return -1; // 返回错误值
} }
// 读取响应数据 // 读取响应数据
QByteArray response = m_tcpSocket->readAll(); QByteArray response = m_tcpSocket->readAll();
if (response.size() < 9) { if (response.size() < 9) {
qDebug() << "响应数据不完整"; qDebug() << "响应数据不完整";
return -1; // 返回错误值 return -1; // 返回错误值
} }
// 解析响应 // 解析响应
QDataStream responseStream(response); QDataStream responseStream(response);
responseStream.setByteOrder(QDataStream::LittleEndian); responseStream.setByteOrder(QDataStream::LittleEndian);
quint16 responseTransactionId; quint16 responseTransactionId;
responseStream >> responseTransactionId; // 事务 ID responseStream >> responseTransactionId; // 事务 ID
quint16 responseProtocolId; quint16 responseProtocolId;
responseStream >> responseProtocolId; // 协议 ID responseStream >> responseProtocolId; // 协议 ID
quint16 responseLength; quint16 responseLength;
responseStream >> responseLength; // 剩余长度 responseStream >> responseLength; // 剩余长度
quint8 responseUnitId; quint8 responseUnitId;
responseStream >> responseUnitId; // 单元 ID responseStream >> responseUnitId; // 单元 ID
quint8 responseFunctionCode; quint8 responseFunctionCode;
responseStream >> responseFunctionCode; // 功能码 responseStream >> responseFunctionCode; // 功能码
quint8 byteCount; quint8 byteCount;
responseStream >> byteCount; // 字节计数 responseStream >> byteCount; // 字节计数
// 检查功能码和字节计数 // 检查功能码和字节计数
if (responseFunctionCode != functionCode || byteCount != 2) { if (responseFunctionCode != functionCode || byteCount != 2) {
qDebug() << "功能码或字节计数不匹配"; qDebug() << "功能码或字节计数不匹配";
return -1; // 返回错误值 return -1; // 返回错误值
} }
// 获取并输出最后四个字节 // 获取并输出最后四个字节
if (response.size() < 2) { if (response.size() < 2) {
qDebug() << "响应数据少于四个字节,无法获取最后四位"; qDebug() << "响应数据少于四个字节,无法获取最后四位";
} }
QByteArray lastFourBytes = response.right(2); // 获取最后2个字节 QByteArray lastFourBytes = response.right(2); // 获取最后2个字节
bool isOk; bool isOk;
int decimalValue = lastFourBytes.toHex().toInt(&isOk, 16); int decimalValue = lastFourBytes.toHex().toInt(&isOk, 16);
return decimalValue; // 返回煤量占比 return decimalValue; // 返回煤量占比
} }
QByteArray CoalDistributBarChartWidget::createModbusTcpRequest() QByteArray CoalDistributBarChartWidget::createModbusTcpRequest() {
{ QByteArray request;
QByteArray request; QDataStream stream(&request, QIODevice::WriteOnly);
QDataStream stream(&request, QIODevice::WriteOnly); stream.setByteOrder(QDataStream::BigEndian); // 使用大端字节序
stream.setByteOrder(QDataStream::BigEndian); // 使用大端字节序
// 构建 Modbus TCP 请求 // 构建 Modbus TCP 请求
quint16 transactionId = 0x0004; // 事务 ID quint16 transactionId = 0x0004; // 事务 ID
quint16 protocolId = 0x0000; // 协议 ID quint16 protocolId = 0x0000; // 协议 ID
quint16 length = 0x0006; // 剩余长度 quint16 length = 0x0006; // 剩余长度
quint8 unitId = 0x01; // 单元 ID quint8 unitId = 0x01; // 单元 ID
quint8 functionCode = 0x03; // 功能码 quint8 functionCode = 0x03; // 功能码
quint8 byteCount = 0x02; // 字节计数 quint8 byteCount = 0x02; // 字节计数
quint16 registerAddress = 0x01BB; // 寄存器地址 700 quint16 registerAddress = 0x01BB; // 寄存器地址 700
quint16 registerCount = 0x0001; // 寄存器数量 quint16 registerCount = 0x0001; // 寄存器数量
// 写入数据 // 写入数据
stream << transactionId; stream << transactionId;
stream << protocolId; stream << protocolId;
stream << length; stream << length;
stream << unitId; stream << unitId;
stream << functionCode; stream << functionCode;
stream << byteCount; stream << byteCount;
stream << registerAddress; stream << registerAddress;
stream << registerCount; stream << registerCount;
return request; // 返回生成的请求报文 return request; // 返回生成的请求报文
} }

View File

@ -1,4 +1,4 @@
#include "coalstatisticschartwidget.h" #include "coalstatisticschartwidget.h"
#include "ui_coalstatisticschartwidget.h" #include "ui_coalstatisticschartwidget.h"
#include <QHttpPart> #include <QHttpPart>
@ -10,324 +10,409 @@
#include <QUrl> #include <QUrl>
#include <QUrlQuery> #include <QUrlQuery>
CoalStatisticsChartWidget::CoalStatisticsChartWidget(QWidget* parent) CoalStatisticsChartWidget::CoalStatisticsChartWidget(QWidget *parent)
: QWidget(parent) : QWidget(parent), ui(new Ui::CoalStatisticsChartWidget) {
, ui(new Ui::CoalStatisticsChartWidget) ui->setupUi(this);
{
ui->setupUi(this);
m_systemSetting = new QSettings("system.ini", QSettings::IniFormat); m_systemSetting = new QSettings("system.ini", QSettings::IniFormat);
initCustomCoalStatisticsBarChart(); ui->dateTimeEdit_startTime->setDateTime(
QDateTime::currentDateTime().addSecs(-8 * 3600));
// initCustomCoalStatisticsBarChart();
initCustomPlotBarChart();
} }
CoalStatisticsChartWidget::~CoalStatisticsChartWidget() CoalStatisticsChartWidget::~CoalStatisticsChartWidget() { delete ui; }
{
delete ui; void CoalStatisticsChartWidget::on_pushButton_coalStatisOk_clicked() {
// 时间范围
QString beginTimeStr = ui->dateTimeEdit_startTime->text();
QString endTimeStr = ui->dateTimeEdit_endTime->text();
// 定义输出格式化后的时间
QString formattedBeginTime;
QString formattedEndTime;
formatTimeRange(beginTimeStr, endTimeStr, formattedBeginTime,
formattedEndTime);
// 统计单位
QString statisticUnit = ui->comboBox_unit->currentText();
m_volumeDataMap.clear();
getCoalStatisInfoByHttpRequest(formattedBeginTime, formattedEndTime,
statisticUnit);
ui->label_totalVolume->clear();
ui->label_totalVolume->setText(QString("煤量总计:%1吨").arg(m_toalValue));
QString volumeDataMapStr = "总数" + QString::number(m_volumeDataMap.size());
emit querySuccessInfo(volumeDataMapStr);
// 更新查询的数据至图表
// updateCoalStatisticsChart(volumeDataMap);
} }
void CoalStatisticsChartWidget::on_pushButton_coalStatisOk_clicked() void CoalStatisticsChartWidget::initCoalStatisticsBarChart() {
{ // 创建图表
// 时间范围 m_chart = new QChart();
QString beginTimeStr = ui->dateTimeEdit_startTime->text(); m_chart->setBackgroundBrush(Qt::transparent);
QString endTimeStr = ui->dateTimeEdit_endTime->text(); m_chart->setMargins(QMargins(0, 0, 0, 0));
m_chart->legend()->hide();
qDebug() << "beginTimeStr " << beginTimeStr; // 创建图表视图
qDebug() << "endTimeStr: " << endTimeStr; m_chartView = new QChartView(m_chart);
m_chartView->setBackgroundBrush(Qt::transparent);
m_chartView->setRenderHint(QPainter::Antialiasing);
m_chartView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// 统计单位 // 创建柱状图数据集
QString statisticUnit = ui->comboBox_unit->currentText(); m_series = new QBarSeries();
m_chart->addSeries(m_series);
// 创建 QDateTime 对象 // // 初始化 QDateTimeAxis 作为 X 轴
QDateTime beginTime = QDateTime::fromString(beginTimeStr, "yyyy/MM/d HH:mm"); // m_axisX = new QDateTimeAxis();
QDateTime endTime = QDateTime::fromString(endTimeStr, "yyyy/MM/d HH:mm"); // m_axisX->setFormat("yyyy-MM-dd HH"); // 设置时间格式
// // m_axisX->setTitleText("时间");
// m_axisX->setLabelsColor(Qt::gray);
// 格式化为 "yyyy-MM-d H" 形式 // // 设置 X 轴范围为最近6小时
QString formattedBeginTime = beginTime.toString("yyyy-MM-dd HH"); // QDateTime currentTime = QDateTime::currentDateTime();
QString formattedEndTime = endTime.toString("yyyy-MM-dd HH"); // QDateTime startTime = currentTime.addSecs(-6 * 3600); // 当前时间前6小时
// m_axisX->setRange(startTime, currentTime);
QString startTimestr = "起始时间" + formattedBeginTime; // m_chart->addAxis(m_axisX, Qt::AlignBottom);
QString endTimestr = "终止时间" + formattedEndTime; // m_series->attachAxis(m_axisX);
emit querySuccessInfo(startTimestr); // 设置Y轴
emit querySuccessInfo(endTimestr); m_axisY = new QValueAxis;
m_axisY->setTitleText("");
m_axisY->setLabelsColor(Qt::gray);
m_axisY->setRange(0, 100);
m_chart->addAxis(m_axisY, Qt::AlignLeft);
m_series->attachAxis(m_axisY);
// 输出格式化后的时间 // 布局设置
qDebug() << "Formatted Begin Time: " << formattedBeginTime; QVBoxLayout *layout =
qDebug() << "Formatted End Time: " << formattedEndTime; static_cast<QVBoxLayout *>(ui->widget_coalChart->layout());
qDebug() << "statisticUnit:" << statisticUnit; 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) {
QMap<QString, double> volumeDataMap; layout->addWidget(m_chartView);
}
getCoalStatisInfoByHttpRequest(formattedBeginTime, formattedEndTime, statisticUnit, volumeDataMap);
ui->label_totalVolume->clear();
ui->label_totalVolume->setText(QString("煤量总计:%1吨").arg(m_toalValue));
// 更新查询的数据至图表
// updateCoalStatisticsChart(volumeDataMap);
} }
void CoalStatisticsChartWidget::initCoalStatisticsBarChart() void CoalStatisticsChartWidget::formatTimeRange(const QString &beginTimeStr,
{ const QString &endTimeStr,
// 创建图表 QString &formattedBeginTime,
m_chart = new QChart(); QString &formattedEndTime) {
m_chart->setBackgroundBrush(Qt::transparent); // 创建 QDateTime 对象
m_chart->setMargins(QMargins(0, 0, 0, 0)); QDateTime beginTime = QDateTime::fromString(beginTimeStr, "yyyy/MM/d HH:mm");
m_chart->legend()->hide(); QDateTime endTime = QDateTime::fromString(endTimeStr, "yyyy/MM/d HH:mm");
// 创建图表视图 // 判断转换是否成功
m_chartView = new QChartView(m_chart); if (!beginTime.isValid() || !endTime.isValid()) {
m_chartView->setBackgroundBrush(Qt::transparent); qWarning() << "Invalid time format!";
m_chartView->setRenderHint(QPainter::Antialiasing); return;
m_chartView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); }
// 创建柱状图数据集 // 格式化为 "yyyy-MM-dd HH" 形式
m_series = new QBarSeries(); formattedBeginTime = beginTime.toString("yyyy-MM-dd HH");
m_chart->addSeries(m_series); formattedEndTime = endTime.toString("yyyy-MM-dd HH");
// // 初始化 QDateTimeAxis 作为 X 轴
// m_axisX = new QDateTimeAxis();
// m_axisX->setFormat("yyyy-MM-dd HH"); // 设置时间格式
// // m_axisX->setTitleText("时间");
// m_axisX->setLabelsColor(Qt::gray);
// // 设置 X 轴范围为最近6小时
// QDateTime currentTime = QDateTime::currentDateTime();
// QDateTime startTime = currentTime.addSecs(-6 * 3600); // 当前时间前6小时
// m_axisX->setRange(startTime, currentTime);
// m_chart->addAxis(m_axisX, Qt::AlignBottom);
// m_series->attachAxis(m_axisX);
// 设置Y轴
m_axisY = new QValueAxis;
m_axisY->setTitleText("");
m_axisY->setLabelsColor(Qt::gray);
m_axisY->setRange(0, 100);
m_chart->addAxis(m_axisY, Qt::AlignLeft);
m_series->attachAxis(m_axisY);
// 布局设置
QVBoxLayout* layout = static_cast<QVBoxLayout*>(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);
}
} }
QList<QString> CoalStatisticsChartWidget::getLastSixFullHours(const QDateTime& currentTime) QList<QString>
{ CoalStatisticsChartWidget::getLastSixFullHours(const QDateTime &currentTime) {
// 将当前时间设置为整点 // 将当前时间设置为整点
QDateTime roundedTime = currentTime; QDateTime roundedTime = currentTime;
roundedTime.setTime(QTime(currentTime.time().hour(), 0)); // 设置时间到整点 roundedTime.setTime(QTime(currentTime.time().hour(), 0)); // 设置时间到整点
bool insertTime = false; // 用于控制每隔一个插入时间其他插入0 bool insertTime = false; // 用于控制每隔一个插入时间其他插入0
// 计算距当前整点数的前六个小时 // 计算距当前整点数的前六个小时
QList<QString> timeList; QList<QString> timeList;
for (int i = 6; i >= 1; --i) { for (int i = 6; i >= 1; --i) {
QDateTime prevHour = roundedTime.addSecs(-i * 3600); // 向前推算每个整点 QDateTime prevHour = roundedTime.addSecs(-i * 3600); // 向前推算每个整点
timeList.append(prevHour.toString("H")); timeList.append(prevHour.toString("YYYY/MM/dd H"));
}
return timeList;
}
void CoalStatisticsChartWidget::initCustomCoalStatisticsBarChart() {
// 创建图表
m_chart = new QChart();
m_chart->setBackgroundBrush(Qt::transparent);
m_chart->setMargins(QMargins(0, 0, 0, 0));
m_chart->legend()->hide();
// 创建图表视图
m_chartView = new QChartView(m_chart);
m_chartView->setBackgroundBrush(Qt::transparent);
m_chartView->setRenderHint(QPainter::Antialiasing);
m_chartView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// 创建柱状图数据集
m_series = new QBarSeries();
m_chart->addSeries(m_series);
// 创建X轴
m_axisX = new QBarCategoryAxis();
m_axisX->setLabelsColor(Qt::gray);
m_axisX->setLineVisible(true);
QDateTime currentTime = QDateTime::currentDateTime();
QList<QString> timeList = getLastSixFullHours(currentTime);
m_axisX->append(timeList);
m_chart->addAxis(m_axisX, Qt::AlignBottom); // 添加X轴到图表
m_series->attachAxis(m_axisX); // 将X轴与柱状图数据集关联
// 设置Y轴
m_axisY = new QValueAxis;
m_axisY->setTitleText("");
m_axisY->setLabelsColor(Qt::gray);
m_axisY->setRange(0, 100);
m_chart->addAxis(m_axisY, Qt::AlignLeft);
m_series->attachAxis(m_axisY);
// 布局设置
QVBoxLayout *layout =
static_cast<QVBoxLayout *>(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);
}
}
void CoalStatisticsChartWidget::initCustomPlotBarChart() {
// 创建 QCustomPlot 图表
m_customPlot =
new QCustomPlot(ui->widget_coalChart); // 假设 ui->widget_coalChart 是容器
m_customPlot->setBackground(Qt::transparent); // 设置背景透明
// 设置布局
QVBoxLayout *layout =
static_cast<QVBoxLayout *>(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_customPlot) == -1) {
layout->addWidget(m_customPlot); // 将 QCustomPlot 添加到布局中
}
// 设置 X 轴
m_customPlot->xAxis->setLabel("时间");
m_customPlot->xAxis->setBasePen(QPen(Qt::gray)); // 设置轴线颜色
m_customPlot->xAxis->setTickPen(QPen(Qt::gray)); // 设置刻度线颜色
m_customPlot->xAxis->setSubTickPen(QPen(Qt::gray)); // 设置子刻度线颜色
m_customPlot->xAxis->setTickLabelColor(Qt::gray); // 设置刻度标签颜色
m_customPlot->xAxis->setTickLabelRotation(
60); // 设置刻度标签的旋转角度,避免重叠
// 设置 Y 轴
m_customPlot->yAxis->setLabel("");
m_customPlot->yAxis->setBasePen(QPen(Qt::gray));
m_customPlot->yAxis->setTickPen(QPen(Qt::gray));
m_customPlot->yAxis->setSubTickPen(QPen(Qt::gray));
m_customPlot->yAxis->setTickLabelColor(Qt::gray);
m_customPlot->yAxis->setRange(0, 100); // 设置 Y 轴的范围
// 创建柱状图
m_barGraph =
new QCPBars(m_customPlot->xAxis, m_customPlot->yAxis); // 创建柱状图对象
m_barGraph->setWidth(0.2); // 设置柱子的宽度
m_barGraph->setPen(QPen(Qt::transparent)); // 设置柱子没有边框
m_barGraph->setBrush(QColor(0, 120, 255)); // 设置柱子的颜色
// 获取时间列表并设置到 X 轴
QDateTime currentTime = QDateTime::currentDateTime();
QList<QString> timeList = getLastSixFullHours(currentTime);
QVector<QString> ticks;
QVector<QString> labels;
for (int i = 0; i < timeList.size(); ++i) {
ticks.append(timeList[i]); // 设置刻度的位置
// labels.append(timeList[i]); // 设置刻度标签(时间)
// m_customPlot->xAxis->setLabel(timeList[i]);
}
m_customPlot->xAxis->setTicks(true); // 设置 X 轴刻度的位置
m_customPlot->xAxis->setTickLabels(true); // 设置刻度标签
// 设置 Y 轴的数据,这里用随机数作为示例
QVector<double> data; // Y 轴的数据
for (int i = 0; i < timeList.size(); ++i) {
data.append(rand() % 100); // 使用随机数填充数据,实际应用中应替换为真实数据
}
m_barGraph->setData(ticks, data); // 设置柱状图的数据
// 重新绘制图表
m_customPlot->replot();
}
void CoalStatisticsChartWidget::getCoalStatisInfoByHttpRequest(
const QString &beginTime, const QString &endTime,
const QString &statisticUnit) {
// 使用类成员变量 QNetworkAccessManager
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QString coalStaticUrl =
m_systemSetting->value("coalStaticInterface/url").toString();
// URL
QUrl url(coalStaticUrl);
QNetworkRequest request(url);
// Form data
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
// begin_time 参数
QHttpPart beginTimePart;
beginTimePart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=\"begin_time\""));
beginTimePart.setBody(beginTime.toUtf8());
// end_time 参数
QHttpPart endTimePart;
endTimePart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=\"end_time\""));
endTimePart.setBody(endTime.toUtf8());
// 统计单位参数
QHttpPart statisticUnitPart;
statisticUnitPart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=\"statistic_unit\""));
statisticUnitPart.setBody(statisticUnit.toUtf8());
// 将表单字段附加到 multipart 请求体中
multiPart->append(beginTimePart);
multiPart->append(endTimePart);
multiPart->append(statisticUnitPart);
// 发送 POST 请求
QNetworkReply *reply = manager->post(request, multiPart);
// 连接信号和槽
QObject::connect(reply, &QNetworkReply::finished, [this, reply, multiPart]() {
if (reply->error() == QNetworkReply::NoError) {
// 处理成功的响应
QByteArray responseData = reply->readAll();
QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
QJsonObject jsonObj = jsonResponse.object();
int code = jsonObj["code"].toInt();
QString message = jsonObj["message"].toString();
QJsonObject data = jsonObj["data"].toObject();
m_toalValue = data["total_volum"].toDouble();
QJsonObject statisticUnitVolum = data["statistic_unit_volum"].toObject();
int statisticUnitVolumSize = statisticUnitVolum.count();
QString statisticUnitVolumSizeString =
"查询结果数" + QString::number(statisticUnitVolumSize);
emit querySuccessInfo(statisticUnitVolumSizeString);
QString totalVolumeString = "总吨数" + QString::number(m_toalValue);
emit querySuccessInfo(totalVolumeString);
// 遍历 statistic_unit_volum 中的键值对并存入 volumeDataMap
for (const QString &key : statisticUnitVolum.keys()) {
double value = statisticUnitVolum.value(key).toDouble();
m_volumeDataMap.insert(key, value);
}
qDebug() << "Code:" << code;
qDebug() << "Message:" << message;
qDebug() << "Total Volume:" << m_toalValue;
} else {
// 处理错误
QString errorString = reply->errorString();
emit querySuccessInfo(errorString);
qDebug() << "Error:" << errorString;
} }
return timeList; // 清理资源
reply->deleteLater();
multiPart->deleteLater();
});
} }
void CoalStatisticsChartWidget::initCustomCoalStatisticsBarChart() void CoalStatisticsChartWidget::updateCoalStatisticsChart(
{ const QMap<QString, double> &volumeDataMap) {
// 创建图表 qDebug() << "更新图表程序" << volumeDataMap.size();
m_chart = new QChart();
m_chart->setBackgroundBrush(Qt::transparent);
m_chart->setMargins(QMargins(0, 0, 0, 0));
m_chart->legend()->hide();
// 创建图表视图 // 清除旧数据
m_chartView = new QChartView(m_chart); m_series->clear();
m_chartView->setBackgroundBrush(Qt::transparent);
m_chartView->setRenderHint(QPainter::Antialiasing);
m_chartView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// 创建柱状图数据集 // 创建新的数据集
m_series = new QBarSeries(); QBarSet *set = new QBarSet("煤量");
m_chart->addSeries(m_series);
// 创建X轴 // 用于存储时间标签
m_axisX = new QBarCategoryAxis(); QList<QString> categories;
m_axisX->setLabelsColor(Qt::gray);
m_axisX->setLineVisible(true);
QDateTime currentTime = QDateTime::currentDateTime(); // 将字符串格式的时间转换为 QDateTime并准备时间标签
QList<QString> timeList = getLastSixFullHours(currentTime); for (auto it = volumeDataMap.begin(); it != volumeDataMap.end(); ++it) {
m_axisX->append(timeList); // 将时间字符串转换为 QDateTime 对象
m_chart->addAxis(m_axisX, Qt::AlignBottom); // 添加X轴到图表 QDateTime time = QDateTime::fromString(it.key(), "yyyy-MM-dd HH");
m_series->attachAxis(m_axisX); // 将X轴与柱状图数据集关联
// 设置Y轴 // 如果转换失败,跳过这个数据项
m_axisY = new QValueAxis; if (!time.isValid()) {
m_axisY->setTitleText(""); continue;
m_axisY->setLabelsColor(Qt::gray);
m_axisY->setRange(0, 100);
m_chart->addAxis(m_axisY, Qt::AlignLeft);
m_series->attachAxis(m_axisY);
// 布局设置
QVBoxLayout* layout = static_cast<QVBoxLayout*>(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);
}
}
void CoalStatisticsChartWidget::getCoalStatisInfoByHttpRequest(const QString& beginTime, const QString& endTime, const QString& statisticUnit, QMap<QString, double>& volumeDataMap)
{
// 使用类成员变量 QNetworkAccessManager
QNetworkAccessManager* manager = new QNetworkAccessManager(this);
QString coalStaticUrl = m_systemSetting->value("coalStaticInterface/url").toString();
// URL
QUrl url(coalStaticUrl);
QNetworkRequest request(url);
// Form data
QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
// begin_time 参数
QHttpPart beginTimePart;
beginTimePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"begin_time\""));
beginTimePart.setBody(beginTime.toUtf8());
// end_time 参数
QHttpPart endTimePart;
endTimePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"end_time\""));
endTimePart.setBody(endTime.toUtf8());
// 统计单位参数
QHttpPart statisticUnitPart;
statisticUnitPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"statistic_unit\""));
statisticUnitPart.setBody(statisticUnit.toUtf8());
// 将表单字段附加到 multipart 请求体中
multiPart->append(beginTimePart);
multiPart->append(endTimePart);
multiPart->append(statisticUnitPart);
// 发送 POST 请求
QNetworkReply* reply = manager->post(request, multiPart);
// 连接信号和槽
QObject::connect(reply, &QNetworkReply::finished, [this, reply, multiPart, &volumeDataMap]() {
if (reply->error() == QNetworkReply::NoError) {
// 处理成功的响应
QByteArray responseData = reply->readAll();
QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
QJsonObject jsonObj = jsonResponse.object();
int code = jsonObj["code"].toInt();
QString message = jsonObj["message"].toString();
QJsonObject data = jsonObj["data"].toObject();
m_toalValue = data["total_volum"].toDouble();
QJsonObject statisticUnitVolum = data["statistic_unit_volum"].toObject();
int statisticUnitVolumSize = statisticUnitVolum.count();
QString statisticUnitVolumSizeString = "查询结果数" + QString::number(statisticUnitVolumSize);
emit querySuccessInfo(statisticUnitVolumSizeString);
QString totalVolumeString = "总吨数" + QString::number(m_toalValue);
emit querySuccessInfo(totalVolumeString);
// 遍历 statistic_unit_volum 中的键值对并存入 volumeDataMap
// for (const QString& key : statisticUnitVolum.keys()) {
// double value = statisticUnitVolum.value(key).toDouble();
// volumeDataMap.insert(key, value);
// }
qDebug() << "Code:" << code;
qDebug() << "Message:" << message;
qDebug() << "Total Volume:" << m_toalValue;
} else {
// 处理错误
QString errorString = reply->errorString();
emit querySuccessInfo(errorString);
qDebug() << "Error:" << errorString;
}
// 清理资源
reply->deleteLater();
multiPart->deleteLater();
});
}
void CoalStatisticsChartWidget::updateCoalStatisticsChart(const QMap<QString, double>& volumeDataMap)
{
qDebug() << "更新图表程序" << volumeDataMap.size();
// 清除旧数据
m_series->clear();
// 创建新的数据集
QBarSet* set = new QBarSet("煤量");
// 用于存储时间标签
QList<QString> categories;
// 将字符串格式的时间转换为 QDateTime并准备时间标签
for (auto it = volumeDataMap.begin(); it != volumeDataMap.end(); ++it) {
// 将时间字符串转换为 QDateTime 对象
QDateTime time = QDateTime::fromString(it.key(), "yyyy-MM-dd HH");
// 如果转换失败,跳过这个数据项
if (!time.isValid()) {
continue;
}
*set << it.value(); // 将数据量加入到数据集
// 根据选择的时间单位,格式化时间标签
QString label;
if (ui->comboBox_unit->currentText() == QStringLiteral("")) {
label = time.toString("H");
} else if (ui->comboBox_unit->currentText() == QStringLiteral("")) {
label = time.toString("dd"); // 使用 'dd' 来格式化日期
} else if (ui->comboBox_unit->currentText() == QStringLiteral("")) {
label = time.toString("MM"); // 使用 'MM' 来格式化月份
} else if (ui->comboBox_unit->currentText() == QStringLiteral("")) {
label = time.toString("yyyy"); // 使用 'yyyy' 来格式化年份
}
categories.append(label); // 将时间标签添加到列表
} }
// 将数据集添加到 series *set << it.value(); // 将数据量加入到数据集
m_series->append(set);
// 使用 QCategoryAxis 设置 X 轴为字符串格式的时间标签 // 根据选择的时间单位,格式化时间标签
m_axisX->clear(); // 清除之前的标签 QString label;
m_axisX->append(categories); // 将新的时间标签添加到 X 轴 if (ui->comboBox_unit->currentText() == QStringLiteral("")) {
label = time.toString("H");
} else if (ui->comboBox_unit->currentText() == QStringLiteral("")) {
label = time.toString("dd"); // 使用 'dd' 来格式化日期
} else if (ui->comboBox_unit->currentText() == QStringLiteral("")) {
label = time.toString("MM"); // 使用 'MM' 来格式化月份
} else if (ui->comboBox_unit->currentText() == QStringLiteral("")) {
label = time.toString("yyyy"); // 使用 'yyyy' 来格式化年份
}
// 将 X 轴绑定到 series categories.append(label); // 将时间标签添加到列表
// m_chart->addAxis(m_axisX, Qt::AlignBottom); }
// m_series->attachAxis(m_axisX);
// 更新 Y 轴范围 // 将数据集添加到 series
double maxValue = *std::max_element(volumeDataMap.begin(), volumeDataMap.end()); m_series->append(set);
m_axisY->setRange(0, maxValue + 10); // 设置为最大值并留出余量
// 使用 QCategoryAxis 设置 X 轴为字符串格式的时间标签
m_axisX->clear(); // 清除之前的标签
m_axisX->append(categories); // 将新的时间标签添加到 X 轴
// 将 X 轴绑定到 series
// m_chart->addAxis(m_axisX, Qt::AlignBottom);
// m_series->attachAxis(m_axisX);
// 更新 Y 轴范围
double maxValue =
*std::max_element(volumeDataMap.begin(), volumeDataMap.end());
m_axisY->setRange(0, maxValue + 10); // 设置为最大值并留出余量
} }

View File

@ -1,6 +1,8 @@
#ifndef COALSTATISTICSCHARTWIDGET_H #ifndef COALSTATISTICSCHARTWIDGET_H
#define COALSTATISTICSCHARTWIDGET_H #define COALSTATISTICSCHARTWIDGET_H
#include "component/qcustomplot/qcustomplot.h"
#include <QWidget> #include <QWidget>
#include <QtCharts> #include <QtCharts>
@ -10,78 +12,100 @@ class CoalStatisticsChartWidget;
} }
enum TimeUnit { enum TimeUnit {
Hour = 0, // 时 Hour = 0, // 时
Day = 1, // 天 Day = 1, // 天
Month = 2, // 月 Month = 2, // 月
Year = 3 // 年 Year = 3 // 年
}; };
class CoalStatisticsChartWidget : public QWidget { class CoalStatisticsChartWidget : public QWidget {
Q_OBJECT Q_OBJECT
public: public:
explicit CoalStatisticsChartWidget(QWidget* parent = nullptr); explicit CoalStatisticsChartWidget(QWidget *parent = nullptr);
~CoalStatisticsChartWidget(); ~CoalStatisticsChartWidget();
signals: signals:
void querySuccessInfo(QString& queryInfo); void querySuccessInfo(QString &queryInfo);
private slots: private slots:
/** /**
* @brief on_pushButton_coalStatisOk_clicked * @brief on_pushButton_coalStatisOk_clicked
*/ */
void on_pushButton_coalStatisOk_clicked(); void on_pushButton_coalStatisOk_clicked();
private: private:
/** /**
* @brief initCoalStatisticsBarChart * @brief initCoalStatisticsBarChart
*/ */
void initCoalStatisticsBarChart(); void initCoalStatisticsBarChart();
/** /**
* @brief getLastSixFullHours * @brief formatTimeRange
* @param currentTime * @param beginTimeStr
* @return * @param endTimeStr
*/ * @param formattedBeginTime
QList<QString> getLastSixFullHours(const QDateTime& currentTime); * @param formattedEndTime
*/
void formatTimeRange(const QString &beginTimeStr, const QString &endTimeStr,
QString &formattedBeginTime, QString &formattedEndTime);
/** /**
* @brief initCustomCoalStatisticsBarChart * @brief getLastSixFullHours
*/ * @param currentTime
void initCustomCoalStatisticsBarChart(); * @return
*/
QList<QString> getLastSixFullHours(const QDateTime &currentTime);
/** /**
* @brief getCoalStatisInfoByHttpRequest Http请求获取煤量统计信息 * @brief initCustomCoalStatisticsBarChart
* @param startTime */
* @param endTime void initCustomCoalStatisticsBarChart();
* @param statisticUnit
* @param volumeDataMap Map
*/
void getCoalStatisInfoByHttpRequest(const QString& startTime, const QString& endTime, const QString& statisticUnit, QMap<QString, double>& volumeDataMap);
/** void initCustomPlotBarChart();
* @brief updateCoalStatisticsChart
* @param volumeDataMap /**
*/ * @brief getCoalStatisInfoByHttpRequest Http请求获取煤量统计信息
void updateCoalStatisticsChart(const QMap<QString, double>& volumeDataMap); * @param startTime
* @param endTime
* @param statisticUnit
* @param volumeDataMap Map
*/
void getCoalStatisInfoByHttpRequest(const QString &startTime,
const QString &endTime,
const QString &statisticUnit);
/**
* @brief updateCoalStatisticsChart
* @param volumeDataMap
*/
void updateCoalStatisticsChart(const QMap<QString, double> &volumeDataMap);
private: private:
Ui::CoalStatisticsChartWidget* ui; Ui::CoalStatisticsChartWidget *ui;
QChart* m_chart; QChart *m_chart;
QChartView* m_chartView; QChartView *m_chartView;
QBarSeries* m_series; QBarSeries *m_series;
QBarCategoryAxis* m_axisX; QBarCategoryAxis *m_axisX;
// QDateTimeAxis* m_axisX; // QDateTimeAxis* m_axisX;
// QValueAxis* m_axisX; // QValueAxis* m_axisX;
QValueAxis* m_axisY; QValueAxis *m_axisY;
QTimer* m_timer; QTimer *m_timer;
QSettings* m_systemSetting; QCustomPlot *m_customPlot;
QCPBars *m_barGraph;
double m_toalValue = 0.0; QSettings *m_systemSetting;
double m_toalValue = 0.0;
/**
* @brief m_volumeDataMap
*/
QMap<QString, double> m_volumeDataMap;
}; };
#endif // COALSTATISTICSCHARTWIDGET_H #endif // COALSTATISTICSCHARTWIDGET_H