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 += charts
QT += network
QT += printsupport
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = HX_CoalFlowDetect
@ -26,6 +28,7 @@ DEFINES += QT_DEPRECATED_WARNINGS
CONFIG += c++11
SOURCES += \
component/qcustomplot/qcustomplot.cpp \
controller/coaldistributmodbusthread.cpp \
main.cpp \
mainwindow.cpp \
@ -38,6 +41,7 @@ SOURCES += \
component/ZDateEdit/ztimeedit.cpp\
HEADERS += \
component/qcustomplot/qcustomplot.h \
controller/coaldistributmodbusthread.h \
mainwindow.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 <QTimer>
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowFlag(Qt::FramelessWindowHint);
this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint);
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
this->setWindowFlag(Qt::FramelessWindowHint);
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; }
bool MainWindow::eventFilter(QObject* watched, QEvent* event)
{
// 处理鼠标按下、释放和移动事件
if (watched == ui->widget_head) {
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->type() == QEvent::MouseButtonPress) {
if (mouseEvent->button() == Qt::LeftButton) {
m_mousePressed = true; // 启动拖拽
m_mousePoint = mouseEvent->globalPos() - this->pos();
bool MainWindow::eventFilter(QObject *watched, QEvent *event) {
// 处理鼠标按下、释放和移动事件
if (watched == ui->widget_head) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->type() == QEvent::MouseButtonPress) {
if (mouseEvent->button() == Qt::LeftButton) {
m_mousePressed = true; // 启动拖拽
m_mousePoint = mouseEvent->globalPos() - this->pos();
this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint | Qt::Window | Qt::WindowStaysOnTopHint);
this->show(); // 确保窗口显示
this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint |
Qt::WindowMinimizeButtonHint | Qt::Window |
Qt::WindowStaysOnTopHint);
this->show(); // 确保窗口显示
return true;
}
} else if (mouseEvent->type() == QEvent::MouseButtonRelease) {
m_mousePressed = false;
return true;
} else if (mouseEvent->type() == QEvent::MouseMove) {
if (m_mousePressed && (mouseEvent->buttons() & Qt::LeftButton)) {
this->move(mouseEvent->globalPos() - m_mousePoint);
return true;
}
} else if (mouseEvent->type() == QEvent::MouseButtonRelease) {
m_mousePressed = false;
return true;
} else if (mouseEvent->type() == QEvent::MouseMove) {
if (m_mousePressed && (mouseEvent->buttons() & Qt::LeftButton)) {
this->move(mouseEvent->globalPos() - m_mousePoint);
// 每次移动时设置为最上方
this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint | Qt::Window | Qt::WindowStaysOnTopHint);
this->show();
return true;
}
}
// 每次移动时设置为最上方
this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint |
Qt::WindowMinimizeButtonHint | Qt::Window |
Qt::WindowStaysOnTopHint);
this->show();
return true;
}
}
}
}
void MainWindow::addBeltWarnInfoToTextEdit(const QString& consoleInfo)
{
qDebug() << consoleInfo;
m_textEditConsoleInfo.append(consoleInfo);
QDateTime startDateTime = QDateTime::currentDateTime();
QString formattedTime = startDateTime.toString("yyyy-MM-dd hh:mm:ss");
void MainWindow::addBeltWarnInfoToTextEdit(const QString &consoleInfo) {
qDebug() << consoleInfo;
m_textEditConsoleInfo.append(consoleInfo);
QDateTime startDateTime = QDateTime::currentDateTime();
QString formattedTime = startDateTime.toString("yyyy-MM-dd hh:mm:ss");
if (m_textEditConsoleInfo.isEmpty())
return;
QString lastConsoleInfo = m_textEditConsoleInfo.last();
if (m_textEditConsoleInfo.isEmpty())
return;
QString lastConsoleInfo = m_textEditConsoleInfo.last();
// qint64 timeDifferenceInMilliseconds = m_previousConsleInfoDateTime.secsTo(startDateTime);
// qint64 timeDifferenceInMilliseconds =
// m_previousConsleInfoDateTime.secsTo(startDateTime);
// if ((lastConsoleInfo == consoleInfo) && timeDifferenceInMilliseconds < 2)
// return;
// if ((lastConsoleInfo == consoleInfo) && timeDifferenceInMilliseconds <
// 2)
// return;
QString consoleInfoResult = QStringLiteral("[%1]%2").arg(formattedTime).arg(consoleInfo);
ui->textEdit_beltWarnInfo->append(consoleInfoResult);
QString 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_max_clicked()
{
if (isFullScreen()) {
this->showMaximized();
} else {
this->showFullScreen();
}
void MainWindow::on_pushButton_max_clicked() {
if (isFullScreen()) {
this->showMaximized();
} else {
this->showFullScreen();
}
}
void MainWindow::on_pushButton_min_clicked() { this->showMinimized(); }
void MainWindow::calendarLoopPlay()
{
ui->label_calendar->clear();
QTimer* timer_calendar = new QTimer(this);
connect(timer_calendar, &QTimer::timeout, this, [this]() {
QDateTime time = QDateTime::currentDateTime();
QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
ui->label_calendar->setText(str);
});
timer_calendar->start(1000); //每一秒溢出一次进入槽函数
void MainWindow::calendarLoopPlay() {
ui->label_calendar->clear();
QTimer *timer_calendar = new QTimer(this);
connect(timer_calendar, &QTimer::timeout, this, [this]() {
QDateTime time = QDateTime::currentDateTime();
QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
ui->label_calendar->setText(str);
});
timer_calendar->start(1000); //每一秒溢出一次进入槽函数
}
void MainWindow::setSystemTitle()
{
QString titleName = m_systemSetting->value("system/name").toString();
if (!titleName.isEmpty()) {
ui->label_title->clear();
ui->label_title->setText(titleName);
}
void MainWindow::createSystemINI() {
// 写入数据到INI文件
// 判断并设置 "system/name"
if (!m_systemSetting->contains("system/name")) {
m_systemSetting->setValue("system/name", "煤流监测平台");
}
// 判断并设置 "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()
{
ui->textEdit_beltWarnInfo->document()->setMaximumBlockCount(100);
ui->textEdit_beltWarnInfo->setReadOnly(true);
ui->textEdit_beltWarnInfo->setTextInteractionFlags(Qt::NoTextInteraction);
void MainWindow::setSystemTitle() {
QString titleName = m_systemSetting->value("system/name").toString();
if (!titleName.isEmpty()) {
ui->label_title->clear();
ui->label_title->setText(titleName);
}
}
void MainWindow::addcoalDistributChart()
{
// addBeltWarnInfoToTextEdit("添加煤流分布窗口成功!");
ui->textEdit_beltWarnInfo->append("添加煤流分布窗口成功!");
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::setBeltWarnInfoTextEditStyle() {
ui->textEdit_beltWarnInfo->document()->setMaximumBlockCount(100);
ui->textEdit_beltWarnInfo->setReadOnly(true);
ui->textEdit_beltWarnInfo->setTextInteractionFlags(Qt::NoTextInteraction);
}
void MainWindow::addbeltSpeedChat()
{
ui->textEdit_beltWarnInfo->append("添加皮带机速度曲线窗口成功!");
BeltSpeedLineWidget* beltSpeedLineWidget = new BeltSpeedLineWidget(this);
// 检查布局是否已设置
if (!ui->widget_beltSpeedChart->layout()) {
ui->widget_beltSpeedChart->setLayout(new QVBoxLayout);
}
beltSpeedLineWidget->setContentsMargins(0, 0, 0, 0);
ui->widget_beltSpeedChart->layout()->addWidget(beltSpeedLineWidget);
void MainWindow::addcoalDistributChart() {
// addBeltWarnInfoToTextEdit("添加煤流分布窗口成功!");
ui->textEdit_beltWarnInfo->append("添加煤流分布窗口成功!");
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::addCoalStatisticsChart()
{
ui->textEdit_beltWarnInfo->append("添加煤量统计窗口成功!");
CoalStatisticsChartWidget* coalStatisticsChartWidget = new CoalStatisticsChartWidget(this);
// 检查布局是否已设置
if (!ui->widget_beltSpeedChart->layout()) {
ui->widget_beltSpeedChart->setLayout(new QVBoxLayout);
}
coalStatisticsChartWidget->setContentsMargins(0, 0, 0, 0);
ui->widget_coalStatisticsChart->layout()->addWidget(
coalStatisticsChartWidget);
connect(coalStatisticsChartWidget, &CoalStatisticsChartWidget::querySuccessInfo, this, &MainWindow::addBeltWarnInfoToTextEdit);
void MainWindow::addbeltSpeedChat() {
ui->textEdit_beltWarnInfo->append("添加皮带机速度曲线窗口成功!");
BeltSpeedLineWidget *beltSpeedLineWidget = new BeltSpeedLineWidget(this);
// 检查布局是否已设置
if (!ui->widget_beltSpeedChart->layout()) {
ui->widget_beltSpeedChart->setLayout(new QVBoxLayout);
}
beltSpeedLineWidget->setContentsMargins(0, 0, 0, 0);
ui->widget_beltSpeedChart->layout()->addWidget(beltSpeedLineWidget);
}
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();
void MainWindow::addCoalStatisticsChart() {
ui->textEdit_beltWarnInfo->append("添加煤量统计窗口成功!");
CoalStatisticsChartWidget *coalStatisticsChartWidget =
new CoalStatisticsChartWidget(this);
// 检查布局是否已设置
if (!ui->widget_beltSpeedChart->layout()) {
ui->widget_beltSpeedChart->setLayout(new QVBoxLayout);
}
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 {
Q_OBJECT
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = nullptr);
~MainWindow();
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
protected:
bool eventFilter(QObject* watched, QEvent* event) override;
bool eventFilter(QObject *watched, QEvent *event) override;
public slots:
/**
/**
* @brief
* @param consoleInfo
*/
void addBeltWarnInfoToTextEdit(const QString& consoleInfo);
void addBeltWarnInfoToTextEdit(const QString &consoleInfo);
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:
/**
/**
* @brief calendarLoopPlay
*/
void calendarLoopPlay();
void calendarLoopPlay();
/**
* @brief setSystemTitle
*/
void setSystemTitle();
/**
* @brief createSystemINI
*/
void createSystemINI();
/**
/**
* @brief setSystemTitle
*/
void setSystemTitle();
/**
* @brief setBeltWarnInfoTextEditStyle
*/
void setBeltWarnInfoTextEditStyle();
void setBeltWarnInfoTextEditStyle();
/**
/**
* @brief addcoalDistributChart
*/
void addcoalDistributChart();
void addcoalDistributChart();
/**
/**
* @brief addbeltSpeedChat 线
*/
void addbeltSpeedChat();
void addbeltSpeedChat();
/**
/**
* @brief addCoalStatisticsChart
*/
void addCoalStatisticsChart();
void addCoalStatisticsChart();
/**
/**
* @brief addCoalBeltVideo
*/
void addCoalBeltVideo();
void addCoalBeltVideo();
private:
Ui::MainWindow* ui;
Ui::MainWindow *ui;
/**
/**
* @brief m_textEditConsoleInfo
*/
QList<QString> m_textEditConsoleInfo;
QList<QString> m_textEditConsoleInfo;
/**
/**
* @brief m_previousConsleInfoDateTime
*/
QDateTime m_previousConsleInfoDateTime;
QDateTime m_previousConsleInfoDateTime;
/**
* @brief m_systemSetting
*/
QSettings* m_systemSetting;
/**
* @brief m_systemSetting
*/
QSettings *m_systemSetting;
// 窗口拖拽
QPoint m_mousePoint;
bool m_mousePressed { false };
// 窗口拖拽
QPoint m_mousePoint;
bool m_mousePressed{false};
};
#endif // MAINWINDOW_H

View File

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

View File

@ -1,4 +1,4 @@
#include "coalstatisticschartwidget.h"
#include "coalstatisticschartwidget.h"
#include "ui_coalstatisticschartwidget.h"
#include <QHttpPart>
@ -10,324 +10,409 @@
#include <QUrl>
#include <QUrlQuery>
CoalStatisticsChartWidget::CoalStatisticsChartWidget(QWidget* parent)
: QWidget(parent)
, ui(new Ui::CoalStatisticsChartWidget)
{
ui->setupUi(this);
CoalStatisticsChartWidget::CoalStatisticsChartWidget(QWidget *parent)
: QWidget(parent), ui(new Ui::CoalStatisticsChartWidget) {
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()
{
delete ui;
CoalStatisticsChartWidget::~CoalStatisticsChartWidget() { 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()
{
// 时间范围
QString beginTimeStr = ui->dateTimeEdit_startTime->text();
QString endTimeStr = ui->dateTimeEdit_endTime->text();
void CoalStatisticsChartWidget::initCoalStatisticsBarChart() {
// 创建图表
m_chart = new QChart();
m_chart->setBackgroundBrush(Qt::transparent);
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 对象
QDateTime beginTime = QDateTime::fromString(beginTimeStr, "yyyy/MM/d HH:mm");
QDateTime endTime = QDateTime::fromString(endTimeStr, "yyyy/MM/d HH:mm");
// // 初始化 QDateTimeAxis 作为 X 轴
// m_axisX = new QDateTimeAxis();
// m_axisX->setFormat("yyyy-MM-dd HH"); // 设置时间格式
// // m_axisX->setTitleText("时间");
// m_axisX->setLabelsColor(Qt::gray);
// 格式化为 "yyyy-MM-d H" 形式
QString formattedBeginTime = beginTime.toString("yyyy-MM-dd HH");
QString formattedEndTime = endTime.toString("yyyy-MM-dd HH");
// // 设置 X 轴范围为最近6小时
// QDateTime currentTime = QDateTime::currentDateTime();
// QDateTime startTime = currentTime.addSecs(-6 * 3600); // 当前时间前6小时
// m_axisX->setRange(startTime, currentTime);
QString startTimestr = "起始时间" + formattedBeginTime;
QString endTimestr = "终止时间" + formattedEndTime;
// m_chart->addAxis(m_axisX, Qt::AlignBottom);
// m_series->attachAxis(m_axisX);
emit querySuccessInfo(startTimestr);
emit querySuccessInfo(endTimestr);
// 设置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);
// 输出格式化后的时间
qDebug() << "Formatted Begin Time: " << formattedBeginTime;
qDebug() << "Formatted End Time: " << formattedEndTime;
qDebug() << "statisticUnit:" << statisticUnit;
// 布局设置
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);
// 查询结果信息
QMap<QString, double> volumeDataMap;
getCoalStatisInfoByHttpRequest(formattedBeginTime, formattedEndTime, statisticUnit, volumeDataMap);
ui->label_totalVolume->clear();
ui->label_totalVolume->setText(QString("煤量总计:%1吨").arg(m_toalValue));
// 更新查询的数据至图表
// updateCoalStatisticsChart(volumeDataMap);
if (layout->indexOf(m_chartView) == -1) {
layout->addWidget(m_chartView);
}
}
void CoalStatisticsChartWidget::initCoalStatisticsBarChart()
{
// 创建图表
m_chart = new QChart();
m_chart->setBackgroundBrush(Qt::transparent);
m_chart->setMargins(QMargins(0, 0, 0, 0));
m_chart->legend()->hide();
void CoalStatisticsChartWidget::formatTimeRange(const QString &beginTimeStr,
const QString &endTimeStr,
QString &formattedBeginTime,
QString &formattedEndTime) {
// 创建 QDateTime 对象
QDateTime beginTime = QDateTime::fromString(beginTimeStr, "yyyy/MM/d HH:mm");
QDateTime endTime = QDateTime::fromString(endTimeStr, "yyyy/MM/d HH:mm");
// 创建图表视图
m_chartView = new QChartView(m_chart);
m_chartView->setBackgroundBrush(Qt::transparent);
m_chartView->setRenderHint(QPainter::Antialiasing);
m_chartView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// 判断转换是否成功
if (!beginTime.isValid() || !endTime.isValid()) {
qWarning() << "Invalid time format!";
return;
}
// 创建柱状图数据集
m_series = new QBarSeries();
m_chart->addSeries(m_series);
// // 初始化 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);
}
// 格式化为 "yyyy-MM-dd HH" 形式
formattedBeginTime = beginTime.toString("yyyy-MM-dd HH");
formattedEndTime = endTime.toString("yyyy-MM-dd HH");
}
QList<QString> CoalStatisticsChartWidget::getLastSixFullHours(const QDateTime& currentTime)
{
// 将当前时间设置为整点
QDateTime roundedTime = currentTime;
roundedTime.setTime(QTime(currentTime.time().hour(), 0)); // 设置时间到整点
QList<QString>
CoalStatisticsChartWidget::getLastSixFullHours(const QDateTime &currentTime) {
// 将当前时间设置为整点
QDateTime roundedTime = currentTime;
roundedTime.setTime(QTime(currentTime.time().hour(), 0)); // 设置时间到整点
bool insertTime = false; // 用于控制每隔一个插入时间其他插入0
bool insertTime = false; // 用于控制每隔一个插入时间其他插入0
// 计算距当前整点数的前六个小时
QList<QString> timeList;
for (int i = 6; i >= 1; --i) {
// 计算距当前整点数的前六个小时
QList<QString> timeList;
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()
{
// 创建图表
m_chart = new QChart();
m_chart->setBackgroundBrush(Qt::transparent);
m_chart->setMargins(QMargins(0, 0, 0, 0));
m_chart->legend()->hide();
void CoalStatisticsChartWidget::updateCoalStatisticsChart(
const QMap<QString, double> &volumeDataMap) {
qDebug() << "更新图表程序" << volumeDataMap.size();
// 创建图表视图
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->clear();
// 创建柱状图数据集
m_series = new QBarSeries();
m_chart->addSeries(m_series);
// 创建新的数据集
QBarSet *set = new QBarSet("煤量");
// 创建X轴
m_axisX = new QBarCategoryAxis();
m_axisX->setLabelsColor(Qt::gray);
m_axisX->setLineVisible(true);
// 用于存储时间标签
QList<QString> categories;
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轴与柱状图数据集关联
// 将字符串格式的时间转换为 QDateTime并准备时间标签
for (auto it = volumeDataMap.begin(); it != volumeDataMap.end(); ++it) {
// 将时间字符串转换为 QDateTime 对象
QDateTime time = QDateTime::fromString(it.key(), "yyyy-MM-dd HH");
// 设置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::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); // 将时间标签添加到列表
// 如果转换失败,跳过这个数据项
if (!time.isValid()) {
continue;
}
// 将数据集添加到 series
m_series->append(set);
*set << it.value(); // 将数据量加入到数据集
// 使用 QCategoryAxis 设置 X 轴为字符串格式的时间标签
m_axisX->clear(); // 清除之前的标签
m_axisX->append(categories); // 将新的时间标签添加到 X 轴
// 根据选择的时间单位,格式化时间标签
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' 来格式化年份
}
// 将 X 轴绑定到 series
// m_chart->addAxis(m_axisX, Qt::AlignBottom);
// m_series->attachAxis(m_axisX);
categories.append(label); // 将时间标签添加到列表
}
// 更新 Y 轴范围
double maxValue = *std::max_element(volumeDataMap.begin(), volumeDataMap.end());
m_axisY->setRange(0, maxValue + 10); // 设置为最大值并留出余量
// 将数据集添加到 series
m_series->append(set);
// 使用 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
#include "component/qcustomplot/qcustomplot.h"
#include <QWidget>
#include <QtCharts>
@ -10,78 +12,100 @@ class CoalStatisticsChartWidget;
}
enum TimeUnit {
Hour = 0, // 时
Day = 1, // 天
Month = 2, // 月
Year = 3 // 年
Hour = 0, // 时
Day = 1, // 天
Month = 2, // 月
Year = 3 // 年
};
class CoalStatisticsChartWidget : public QWidget {
Q_OBJECT
Q_OBJECT
public:
explicit CoalStatisticsChartWidget(QWidget* parent = nullptr);
~CoalStatisticsChartWidget();
explicit CoalStatisticsChartWidget(QWidget *parent = nullptr);
~CoalStatisticsChartWidget();
signals:
void querySuccessInfo(QString& queryInfo);
void querySuccessInfo(QString &queryInfo);
private slots:
/**
* @brief on_pushButton_coalStatisOk_clicked
*/
void on_pushButton_coalStatisOk_clicked();
/**
* @brief on_pushButton_coalStatisOk_clicked
*/
void on_pushButton_coalStatisOk_clicked();
private:
/**
* @brief initCoalStatisticsBarChart
*/
void initCoalStatisticsBarChart();
/**
* @brief initCoalStatisticsBarChart
*/
void initCoalStatisticsBarChart();
/**
* @brief getLastSixFullHours
* @param currentTime
* @return
*/
QList<QString> getLastSixFullHours(const QDateTime& currentTime);
/**
* @brief formatTimeRange
* @param beginTimeStr
* @param endTimeStr
* @param formattedBeginTime
* @param formattedEndTime
*/
void formatTimeRange(const QString &beginTimeStr, const QString &endTimeStr,
QString &formattedBeginTime, QString &formattedEndTime);
/**
* @brief initCustomCoalStatisticsBarChart
*/
void initCustomCoalStatisticsBarChart();
/**
* @brief getLastSixFullHours
* @param currentTime
* @return
*/
QList<QString> getLastSixFullHours(const QDateTime &currentTime);
/**
* @brief getCoalStatisInfoByHttpRequest Http请求获取煤量统计信息
* @param startTime
* @param endTime
* @param statisticUnit
* @param volumeDataMap Map
*/
void getCoalStatisInfoByHttpRequest(const QString& startTime, const QString& endTime, const QString& statisticUnit, QMap<QString, double>& volumeDataMap);
/**
* @brief initCustomCoalStatisticsBarChart
*/
void initCustomCoalStatisticsBarChart();
/**
* @brief updateCoalStatisticsChart
* @param volumeDataMap
*/
void updateCoalStatisticsChart(const QMap<QString, double>& volumeDataMap);
void initCustomPlotBarChart();
/**
* @brief getCoalStatisInfoByHttpRequest Http请求获取煤量统计信息
* @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:
Ui::CoalStatisticsChartWidget* ui;
Ui::CoalStatisticsChartWidget *ui;
QChart* m_chart;
QChartView* m_chartView;
QBarSeries* m_series;
QBarCategoryAxis* m_axisX;
// QDateTimeAxis* m_axisX;
// QValueAxis* m_axisX;
QValueAxis* m_axisY;
QChart *m_chart;
QChartView *m_chartView;
QBarSeries *m_series;
QBarCategoryAxis *m_axisX;
// QDateTimeAxis* m_axisX;
// QValueAxis* m_axisX;
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