feat:统计界面

This commit is contained in:
徐超 2024-11-05 17:48:05 +08:00
parent d5fb5c64dd
commit ac69d356e8
9 changed files with 620 additions and 363 deletions

View File

@ -9,7 +9,7 @@ QLable#label_splite{font: bold 14px;}
QWidget#widgetTitle{background-color:#061f65;} QWidget#widgetTitle{background-color:#061f65;}
QWidget#baseWidget{background-color:#EE013B6B;border-radius: 11px;} QWidget#baseWidget{background-color:#EE013B6B;border-radius: 11px;}
QComboBox{background-color: transparent; selection-background-color: transparent; color:#ffffff; font-size: 14px; min-height: 20px; selection-text-align: right;border:0px solid} QComboBox{background-color: transparent; selection-background-color: transparent; color:#ffffff; font-size: 14px; min-height: 20px; border:0px solid}
QComboBox::down-arrow{ image:url(:/component/ZDateEdit/Resources/ComboBoxArrow.png); } QComboBox::down-arrow{ image:url(:/component/ZDateEdit/Resources/ComboBoxArrow.png); }
QComboBox::down-arrow:on{ top: 1px; left: 1px; } QComboBox::drop-down{ width: 26px; border:none; } QComboBox::down-arrow:on{ top: 1px; left: 1px; } QComboBox::drop-down{ width: 26px; border:none; }
QComboBox QAbstractItemView {border: none; outline:0px;} QComboBox QAbstractItemView::item{ height: 26px; min-height:26px;} QComboBox QAbstractItemView {border: none; outline:0px;} QComboBox QAbstractItemView::item{ height: 26px; min-height:26px;}

View File

@ -7,122 +7,175 @@
#include <QDateTime> #include <QDateTime>
#include <QTimer> #include <QTimer>
MainWindow::MainWindow(QWidget *parent) MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent), ui(new Ui::MainWindow) { : QMainWindow(parent)
ui->setupUi(this); , ui(new Ui::MainWindow)
this->setWindowFlag(Qt::FramelessWindowHint); {
this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | ui->setupUi(this);
Qt::WindowMinimizeButtonHint); this->setWindowFlag(Qt::FramelessWindowHint);
this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint);
calendarLoopPlay(); ui->widget_head->installEventFilter(this);
setBeltWarnInfoTextEditStyle(); m_systemSetting = new QSettings("system.ini", QSettings::IniFormat);
addcoalDistributChart(); calendarLoopPlay();
addbeltSpeedChat(); setSystemTitle();
addCoalStatisticsChart(); setBeltWarnInfoTextEditStyle();
addCoalBeltVideo(); addcoalDistributChart();
addbeltSpeedChat();
addCoalStatisticsChart();
addCoalBeltVideo();
} }
MainWindow::~MainWindow() { delete ui; } MainWindow::~MainWindow() { delete ui; }
void MainWindow::addBeltWarnInfoToTextEdit(const QString &consoleInfo) { bool MainWindow::eventFilter(QObject* watched, QEvent* event)
m_textEditConsoleInfo.append(consoleInfo); {
QDateTime startDateTime = QDateTime::currentDateTime(); // 处理鼠标按下、释放和移动事件
QString formattedTime = startDateTime.toString("yyyy-MM-dd hh:mm:ss"); 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();
if (m_textEditConsoleInfo.isEmpty()) this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint | Qt::Window | Qt::WindowStaysOnTopHint);
return; this->show(); // 确保窗口显示
QString lastConsoleInfo = m_textEditConsoleInfo.last();
qint64 timeDifferenceInMilliseconds = return true;
m_previousConsleInfoDateTime.secsTo(startDateTime); }
} 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);
if ((lastConsoleInfo == consoleInfo) && timeDifferenceInMilliseconds < 2) // 每次移动时设置为最上方
return; this->setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint | Qt::Window | Qt::WindowStaysOnTopHint);
this->show();
return true;
}
}
}
}
QString consoleInfoResult = void MainWindow::addBeltWarnInfoToTextEdit(const QString& consoleInfo)
QStringLiteral("[%1]%2").arg(formattedTime).arg(consoleInfo); {
ui->textEdit_beltWarnInfo->append(consoleInfoResult); m_textEditConsoleInfo.append(consoleInfo);
QDateTime startDateTime = QDateTime::currentDateTime();
QString formattedTime = startDateTime.toString("yyyy-MM-dd hh:mm:ss");
m_previousConsleInfoDateTime = QDateTime::currentDateTime(); if (m_textEditConsoleInfo.isEmpty())
return;
QString lastConsoleInfo = m_textEditConsoleInfo.last();
qint64 timeDifferenceInMilliseconds = m_previousConsleInfoDateTime.secsTo(startDateTime);
if ((lastConsoleInfo == consoleInfo) && timeDifferenceInMilliseconds < 2)
return;
QString consoleInfoResult = QStringLiteral("[%1]%2").arg(formattedTime).arg(consoleInfo);
ui->textEdit_beltWarnInfo->append(consoleInfoResult);
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()) { {
this->showMaximized(); if (isFullScreen()) {
} else { this->showMaximized();
this->showFullScreen(); } else {
} 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(); {
QTimer *timer_calendar = new QTimer(this); ui->label_calendar->clear();
connect(timer_calendar, &QTimer::timeout, this, [this]() { QTimer* timer_calendar = new QTimer(this);
QDateTime time = QDateTime::currentDateTime(); connect(timer_calendar, &QTimer::timeout, this, [this]() {
QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd"); QDateTime time = QDateTime::currentDateTime();
ui->label_calendar->setText(str); QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
}); ui->label_calendar->setText(str);
timer_calendar->start(1000); //每一秒溢出一次进入槽函数 });
timer_calendar->start(1000); //每一秒溢出一次进入槽函数
} }
void MainWindow::setBeltWarnInfoTextEditStyle() { void MainWindow::setSystemTitle()
ui->textEdit_beltWarnInfo->document()->setMaximumBlockCount(100); {
ui->textEdit_beltWarnInfo->setReadOnly(true); QString titleName = m_systemSetting->value("system/name").toString();
ui->textEdit_beltWarnInfo->setTextInteractionFlags(Qt::NoTextInteraction); if (!titleName.isEmpty()) {
ui->label_title->clear();
ui->label_title->setText(titleName);
}
} }
void MainWindow::addcoalDistributChart() { void MainWindow::setBeltWarnInfoTextEditStyle()
// addBeltWarnInfoToTextEdit("添加煤流分布窗口成功!"); {
ui->textEdit_beltWarnInfo->append("添加煤流分布窗口成功!"); ui->textEdit_beltWarnInfo->document()->setMaximumBlockCount(100);
ui->textEdit_beltWarnInfo->setReadOnly(true);
CoalDistributBarChartWidget *coalDistributBarChartWidget = ui->textEdit_beltWarnInfo->setTextInteractionFlags(Qt::NoTextInteraction);
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()
ui->textEdit_beltWarnInfo->append("添加皮带机速度曲线窗口成功!"); {
BeltSpeedLineWidget *beltSpeedLineWidget = new BeltSpeedLineWidget(this); // addBeltWarnInfoToTextEdit("添加煤流分布窗口成功!");
// 检查布局是否已设置 ui->textEdit_beltWarnInfo->append("添加煤流分布窗口成功!");
if (!ui->widget_beltSpeedChart->layout()) {
ui->widget_beltSpeedChart->setLayout(new QVBoxLayout); CoalDistributBarChartWidget* coalDistributBarChartWidget = new CoalDistributBarChartWidget(this);
}
beltSpeedLineWidget->setContentsMargins(0, 0, 0, 0); // 检查布局是否已设置
ui->widget_beltSpeedChart->layout()->addWidget(beltSpeedLineWidget); 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() { void MainWindow::addbeltSpeedChat()
ui->textEdit_beltWarnInfo->append("添加煤量统计窗口成功!"); {
CoalStatisticsChartWidget *coalStatisticsChartWidget = ui->textEdit_beltWarnInfo->append("添加皮带机速度曲线窗口成功!");
new CoalStatisticsChartWidget(this); BeltSpeedLineWidget* beltSpeedLineWidget = new BeltSpeedLineWidget(this);
// 检查布局是否已设置 // 检查布局是否已设置
if (!ui->widget_beltSpeedChart->layout()) { if (!ui->widget_beltSpeedChart->layout()) {
ui->widget_beltSpeedChart->setLayout(new QVBoxLayout); ui->widget_beltSpeedChart->setLayout(new QVBoxLayout);
} }
coalStatisticsChartWidget->setContentsMargins(0, 0, 0, 0); beltSpeedLineWidget->setContentsMargins(0, 0, 0, 0);
ui->widget_coalStatisticsChart->layout()->addWidget( ui->widget_beltSpeedChart->layout()->addWidget(beltSpeedLineWidget);
coalStatisticsChartWidget);
} }
void MainWindow::addCoalBeltVideo() { void MainWindow::addCoalStatisticsChart()
QString url = "https://stream7.iqilu.com/10339/upload_transcode/202002/18/" {
"20200218114723HDu3hhxqIT.mp4"; ui->textEdit_beltWarnInfo->append("添加煤量统计窗口成功!");
ui->widget_beltVideo->setUrl(url); CoalStatisticsChartWidget* coalStatisticsChartWidget = new CoalStatisticsChartWidget(this);
ui->widget_beltVideo->open(); // 检查布局是否已设置
if (!ui->widget_beltSpeedChart->layout()) {
ui->widget_beltSpeedChart->setLayout(new QVBoxLayout);
}
coalStatisticsChartWidget->setContentsMargins(0, 0, 0, 0);
ui->widget_coalStatisticsChart->layout()->addWidget(
coalStatisticsChartWidget);
}
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

@ -3,75 +3,93 @@
#include <QDateTime> #include <QDateTime>
#include <QMainWindow> #include <QMainWindow>
#include <QSettings>
namespace Ui { namespace Ui {
class MainWindow; 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:
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
*/
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
*/
QSettings* m_systemSetting;
// 窗口拖拽
QPoint m_mousePoint;
bool m_mousePressed { false };
}; };
#endif // MAINWINDOW_H #endif // MAINWINDOW_H

View File

@ -14,7 +14,7 @@
<string>MainWindow</string> <string>MainWindow</string>
</property> </property>
<property name="windowIcon"> <property name="windowIcon">
<iconset resource="resource.qrc"> <iconset>
<normaloff>:/Resource/image/logo.png</normaloff>:/Resource/image/logo.png</iconset> <normaloff>:/Resource/image/logo.png</normaloff>:/Resource/image/logo.png</iconset>
</property> </property>
<widget class="QWidget" name="centralWidget"> <widget class="QWidget" name="centralWidget">
@ -47,16 +47,15 @@
</property> </property>
<property name="styleSheet"> <property name="styleSheet">
<string notr="true">#widget_head{ <string notr="true">#widget_head{
border-image: url(:/Resource/image/title.png); border-image: url(:/Resource/image/title.png);
}</string> }</string>
</property> </property>
<layout class="QHBoxLayout" name="horizontalLayout_2" stretch="2,4,4,4,0"> <layout class="QHBoxLayout" name="horizontalLayout_2" stretch="2,3,4,3,0">
<property name="spacing"> <property name="spacing">
<number>0</number> <number>0</number>
</property> </property>
<property name="leftMargin"> <property name="leftMargin">
<number>0</number> <number>9</number>
</property> </property>
<property name="rightMargin"> <property name="rightMargin">
<number>0</number> <number>0</number>
@ -78,17 +77,21 @@
</spacer> </spacer>
</item> </item>
<item> <item>
<widget class="QLabel" name="label_title"> <layout class="QHBoxLayout" name="horizontalLayout_56">
<property name="styleSheet"> <item>
<string notr="true">#label_title{ <widget class="QLabel" name="label_title">
<property name="styleSheet">
<string notr="true">#label_title{
color:white; color:white;
font: 24pt &quot;黑体&quot;; font: 24pt &quot;黑体&quot;;
}</string> }</string>
</property> </property>
<property name="text"> <property name="text">
<string>玉泉煤流检测</string> <string>玉泉煤流检测</string>
</property> </property>
</widget> </widget>
</item>
</layout>
</item> </item>
<item> <item>
<spacer name="horizontalSpacer_2"> <spacer name="horizontalSpacer_2">
@ -104,26 +107,30 @@
</spacer> </spacer>
</item> </item>
<item> <item>
<widget class="QLabel" name="label_calendar"> <layout class="QHBoxLayout" name="horizontalLayout_57">
<property name="minimumSize"> <item>
<size> <widget class="QLabel" name="label_calendar">
<width>268</width> <property name="minimumSize">
<height>0</height> <size>
</size> <width>268</width>
</property> <height>0</height>
<property name="styleSheet"> </size>
<string notr="true">#label_calendar{ </property>
<property name="styleSheet">
<string notr="true">#label_calendar{
color:white; color:white;
font: 16pt &quot;黑体&quot;; font: 16pt &quot;黑体&quot;;
}</string> }</string>
</property> </property>
<property name="text"> <property name="text">
<string>2024年10月31日 星期一</string> <string>2024年10月31日 星期一</string>
</property> </property>
<property name="alignment"> <property name="alignment">
<set>Qt::AlignHCenter|Qt::AlignTop</set> <set>Qt::AlignHCenter|Qt::AlignTop</set>
</property> </property>
</widget> </widget>
</item>
</layout>
</item> </item>
<item> <item>
<layout class="QHBoxLayout" name="horizontalLayout_12"> <layout class="QHBoxLayout" name="horizontalLayout_12">
@ -3293,8 +3300,6 @@ QPushButton:pressed{
<container>1</container> <container>1</container>
</customwidget> </customwidget>
</customwidgets> </customwidgets>
<resources> <resources/>
<include location="resource.qrc"/>
</resources>
<connections/> <connections/>
</ui> </ui>

View File

@ -19,224 +19,230 @@
#include <memory> #include <memory>
CoalDistributBarChartWidget::CoalDistributBarChartWidget(QWidget *parent) CoalDistributBarChartWidget::CoalDistributBarChartWidget(QWidget* parent)
: QWidget(parent), m_tcpSocket(new QTcpSocket(this)) { : QWidget(parent)
initializeChart(); , m_tcpSocket(new QTcpSocket(this))
{
initializeChart();
connectTCPSocket(); m_systemSetting = new QSettings("system.ini", QSettings::IniFormat);
setupTimer(); connectTCPSocket();
setupTimer();
} }
CoalDistributBarChartWidget::~CoalDistributBarChartWidget() { CoalDistributBarChartWidget::~CoalDistributBarChartWidget()
if (m_tcpSocket->state() == QAbstractSocket::ConnectedState) { {
m_tcpSocket->disconnectFromHost(); if (m_tcpSocket->state() == QAbstractSocket::ConnectedState) {
m_tcpSocket->waitForDisconnected(); m_tcpSocket->disconnectFromHost();
} m_tcpSocket->waitForDisconnected();
delete m_tcpSocket; }
delete m_tcpSocket;
} }
void CoalDistributBarChartWidget::updateChart() { void CoalDistributBarChartWidget::updateChart()
int radio = getCoalRatioByTCPSocket(); {
// if (radio <= 0 || radio > 100) { int radio = getCoalRatioByTCPSocket();
// return; if (radio <= 0 || radio > 100) {
// } return;
}
int setCount = m_set->count(); int setCount = m_set->count();
qDebug() << "setCount" << setCount; m_set->remove(setCount - 1);
m_set->insert(0, radio);
m_set->remove(setCount - 1);
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); // 定时器设置
connect(m_timer, &QTimer::timeout, this, m_timer = new QTimer(this);
&CoalDistributBarChartWidget::updateChart); connect(m_timer, &QTimer::timeout, this,
m_timer->start(1000); // 每秒更新一次 &CoalDistributBarChartWidget::updateChart);
m_timer->start(1000); // 每秒更新一次
} }
void CoalDistributBarChartWidget::connectTCPSocket() { void CoalDistributBarChartWidget::connectTCPSocket()
QString ipAddress = "192.168.80.101"; // 替换为实际 IP 地址 {
quint16 port = 3000; // Modbus TCP 端口 QString ipAddress = m_systemSetting->value("addr/ip").toString();
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) { {
qDebug() << "未连接到服务器"; if (m_tcpSocket->state() != QAbstractSocket::ConnectedState) {
return -1; // 返回错误值 qDebug() << "未连接到服务器";
} 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; // 返回错误值
} }
qDebug() << "response" << response.toHex(); // 解析响应
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); if (responseFunctionCode != functionCode || byteCount != 2) {
responseStream.setByteOrder(QDataStream::LittleEndian); qDebug() << "功能码或字节计数不匹配";
quint16 responseTransactionId; return -1; // 返回错误值
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) { if (response.size() < 2) {
qDebug() << "功能码或字节计数不匹配"; qDebug() << "响应数据少于四个字节,无法获取最后四位";
return -1; // 返回错误值 }
}
// 获取并输出最后四个字节 QByteArray lastFourBytes = response.right(2); // 获取最后2个字节
if (response.size() < 2) {
qDebug() << "响应数据少于四个字节,无法获取最后四位";
}
QByteArray lastFourBytes = response.right(2); // 获取最后2个字节 bool isOk;
int decimalValue = lastFourBytes.toHex().toInt(&isOk, 16);
bool isOk; return decimalValue; // 返回煤量占比
int decimalValue = lastFourBytes.toHex().toInt(&isOk, 16);
qDebug() << "最后四位:" << decimalValue;
return decimalValue; // 返回煤量占比
} }
QByteArray CoalDistributBarChartWidget::createModbusTcpRequest() { QByteArray CoalDistributBarChartWidget::createModbusTcpRequest()
QByteArray request; {
QDataStream stream(&request, QIODevice::WriteOnly); QByteArray request;
stream.setByteOrder(QDataStream::BigEndian); // 使用大端字节序 QDataStream stream(&request, QIODevice::WriteOnly);
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

@ -3,6 +3,7 @@
#include <QDateTime> #include <QDateTime>
#include <QObject> #include <QObject>
#include <QSettings>
#include <QTimer> #include <QTimer>
#include <QWidget> #include <QWidget>
@ -58,13 +59,9 @@ private:
QBarSet* m_set; QBarSet* m_set;
int currentIndex; // 当前更新的柱子的索引
static const int MaxDataPoints = 300; // 最大数据点数5分钟每秒1条
QList<QDateTime> m_timeLabels; // 存储时间标签
QTcpSocket* m_tcpSocket; QTcpSocket* m_tcpSocket;
QSettings* m_systemSetting;
}; };
#endif // COALDISTRIBUTBARCHARTWIDGET_H #endif // COALDISTRIBUTBARCHARTWIDGET_H

View File

@ -1,6 +1,7 @@
#include "coalstatisticschartwidget.h" #include "coalstatisticschartwidget.h"
#include "ui_coalstatisticschartwidget.h" #include "ui_coalstatisticschartwidget.h"
#include <QHttpPart>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonObject> #include <QJsonObject>
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
@ -15,6 +16,8 @@ CoalStatisticsChartWidget::CoalStatisticsChartWidget(QWidget* parent)
{ {
ui->setupUi(this); ui->setupUi(this);
m_systemSetting = new QSettings("system.ini", QSettings::IniFormat);
initCoalStatisticsBarChart(); initCoalStatisticsBarChart();
getCoalStatisInfoByHttpRequest("2024-09-01 08", "2024-09-02 08"); getCoalStatisInfoByHttpRequest("2024-09-01 08", "2024-09-02 08");
@ -25,6 +28,104 @@ CoalStatisticsChartWidget::~CoalStatisticsChartWidget()
delete ui; delete ui;
} }
void CoalStatisticsChartWidget::on_pushButton_coalStatisOk_clicked()
{
// 时间范围
QString beginTimeStr = ui->dateTimeEdit_startTime->text();
QString endTimeStr = ui->dateTimeEdit_endTime->text();
qDebug() << "beginTimeStr" << beginTimeStr;
qDebug() << "endTimeStr" << endTimeStr;
// 创建 QDateTime 对象
QDateTime beginTime = QDateTime::fromString(beginTimeStr, "yyyy/MM/d HH:mm");
QDateTime endTime = QDateTime::fromString(endTimeStr, "yyyy/MM/d HH:mm");
// 判断是否转换成功
if (!beginTime.isValid() || !endTime.isValid()) {
qDebug() << "Invalid date/time format!";
return;
}
int unitIndex = ui->comboBox_unit->currentIndex();
// 选择的时间单位
switch (unitIndex) {
case TimeUnit::Hour: {
// 计算整时
QList<QDateTime> dateTimes;
int minutes = beginTime.time().minute(); // 获取分钟部分
beginTime = beginTime.addSecs(-minutes * 60); // 向下取整
// 遍历时间范围
while (beginTime <= endTime) {
dateTimes.append(beginTime);
beginTime = beginTime.addSecs(3600); // 增加1小时
}
// 输出结果
for (const QDateTime& dateTime : dateTimes) {
qDebug() << "整小时数" << dateTime.toString("yyyy/MM/d HH:mm");
}
break;
}
case TimeUnit::Day: {
// 计算整天
QList<QDateTime> dateTimes;
beginTime.setTime(QTime(0, 0)); // 将起始时间设置为当天的00:00:00
// 遍历时间范围
while (beginTime <= endTime) {
dateTimes.append(beginTime);
beginTime = beginTime.addDays(1); // 增加1天
}
// 输出结果
for (const QDateTime& dateTime : dateTimes) {
qDebug() << "整天数" << dateTime.toString("yyyy/MM/d");
}
break;
}
case TimeUnit::Month: {
// 计算整月
QList<QDateTime> dateTimes;
beginTime.setDate(QDate(beginTime.date().year(), beginTime.date().month(), 1)); // 设置为当月的1号
// 遍历时间范围
while (beginTime <= endTime) {
dateTimes.append(beginTime);
beginTime = beginTime.addMonths(1); // 增加1个月
}
// 输出结果
for (const QDateTime& dateTime : dateTimes) {
qDebug() << "整月数" << dateTime.toString("yyyy/MM");
}
break;
}
case TimeUnit::Year: {
// 计算整年
QList<QDateTime> dateTimes;
beginTime.setDate(QDate(beginTime.date().year(), 1, 1)); // 设置为当年的1月1日
// 遍历时间范围
while (beginTime <= endTime) {
dateTimes.append(beginTime);
beginTime = beginTime.addYears(1); // 增加1年
}
// 输出结果
for (const QDateTime& dateTime : dateTimes) {
qDebug() << "整年数" << dateTime.toString("yyyy");
}
break;
}
default:
qDebug() << "无效的时间单位!";
break;
}
}
void CoalStatisticsChartWidget::initCoalStatisticsBarChart() void CoalStatisticsChartWidget::initCoalStatisticsBarChart()
{ {
// 创建图表 // 创建图表
@ -45,29 +146,35 @@ void CoalStatisticsChartWidget::initCoalStatisticsBarChart()
m_chart->addSeries(m_series); m_chart->addSeries(m_series);
// 设置X轴为时间 // 设置X轴为时间
QValueAxis* axisX = new QValueAxis; m_axisX = new QDateTimeAxis;
axisX->setRange(1, 300); m_axisX->setFormat("yyyy/MM/d H"); // 设置日期时间格式
axisX->setTickCount(10); // m_axisX->setTitleText("时间");
axisX->setLabelFormat("%d"); m_axisX->setTitleBrush(QBrush(Qt::gray));
axisX->setLinePen(QPen(Qt::gray)); m_axisX->setLinePen(QPen(Qt::gray));
axisX->setLabelsColor(Qt::gray); m_axisX->setLabelsColor(Qt::gray);
axisX->setMinorTickCount(0);
m_chart->addAxis(axisX, Qt::AlignBottom); // 获取当前时间并设置时间范围为最近六个小时
m_series->attachAxis(axisX); QDateTime currentTime = QDateTime::currentDateTime();
QDateTime startTime = currentTime.addSecs(-6 * 3600); // 当前时间减去六个小时
// m_axisX->setLabelsAngle(45);
// 设置X轴时间范围
m_axisX->setRange(startTime, currentTime);
m_chart->addAxis(m_axisX, Qt::AlignBottom);
m_series->attachAxis(m_axisX);
// 设置Y轴为百分比 // 设置Y轴为百分比
QValueAxis* axisY = new QValueAxis; m_axisY = new QValueAxis;
axisY->setTitleText(""); m_axisY->setTitleText("");
axisY->setTitleBrush(QBrush(Qt::gray)); m_axisY->setTitleBrush(QBrush(Qt::gray));
axisY->setLinePen(QPen(Qt::gray)); m_axisY->setLinePen(QPen(Qt::gray));
axisY->setLabelsColor(Qt::gray); m_axisY->setLabelsColor(Qt::gray);
axisY->setRange(0, 100); m_axisY->setRange(0, 100);
m_chart->addAxis(axisY, Qt::AlignLeft); m_chart->addAxis(m_axisY, Qt::AlignLeft);
m_series->attachAxis(axisY); m_series->attachAxis(m_axisY);
m_axisY->setTitleFont(QFont("Arial", 10));
// 设置Y轴标题位置 m_axisY->setTitleVisible(true);
axisY->setTitleFont(QFont("Arial", 10));
axisY->setTitleVisible(true);
// 获取 widget_coalChart 的布局 // 获取 widget_coalChart 的布局
QVBoxLayout* layout = static_cast<QVBoxLayout*>(ui->widget_coalChart->layout()); QVBoxLayout* layout = static_cast<QVBoxLayout*>(ui->widget_coalChart->layout());
@ -89,25 +196,37 @@ void CoalStatisticsChartWidget::initCoalStatisticsBarChart()
void CoalStatisticsChartWidget::getCoalStatisInfoByHttpRequest(const QString& beginTime, const QString& endTime) void CoalStatisticsChartWidget::getCoalStatisInfoByHttpRequest(const QString& beginTime, const QString& endTime)
{ {
QNetworkAccessManager* manager = new QNetworkAccessManager(); // 使用类成员变量 QNetworkAccessManager
QNetworkAccessManager* manager = new QNetworkAccessManager(this);
QString coalStaticUrl = m_systemSetting->value("coalStaticInterface/url").toString();
// URL // URL
QUrl url("http://192.168.5.205:5002/api/get/coal/statistics/value/"); QUrl url(coalStaticUrl);
QNetworkRequest request(url); QNetworkRequest request(url);
// Form data // Form data
QUrlQuery params; QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
params.addQueryItem("begin_time", beginTime);
params.addQueryItem("end_time", endTime);
// 设置请求头 // begin_time 参数
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); 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());
// 将表单字段附加到 multipart 请求体中
multiPart->append(beginTimePart);
multiPart->append(endTimePart);
// 发送 POST 请求 // 发送 POST 请求
QNetworkReply* reply = manager->post(request, params.query(QUrl::FullyEncoded).toUtf8()); QNetworkReply* reply = manager->post(request, multiPart);
// 连接信号和槽 // 连接信号和槽
QObject::connect(reply, &QNetworkReply::finished, [reply]() { QObject::connect(reply, &QNetworkReply::finished, [this, reply, multiPart]() {
if (reply->error() == QNetworkReply::NoError) { if (reply->error() == QNetworkReply::NoError) {
// 处理成功的响应 // 处理成功的响应
QByteArray responseData = reply->readAll(); QByteArray responseData = reply->readAll();
@ -117,15 +236,19 @@ void CoalStatisticsChartWidget::getCoalStatisInfoByHttpRequest(const QString& be
int code = jsonObj["code"].toInt(); int code = jsonObj["code"].toInt();
QString message = jsonObj["message"].toString(); QString message = jsonObj["message"].toString();
QJsonObject data = jsonObj["data"].toObject(); QJsonObject data = jsonObj["data"].toObject();
double totalVolume = data["total_volume"].toDouble(); double totalVolume = data["total_volum"].toDouble();
qDebug() << "Code:" << code; qDebug() << "Code:" << code;
qDebug() << "Message:" << message; qDebug() << "Message:" << message;
qDebug() << "Total Volume:" << totalVolume; qDebug() << "Total Volume:" << totalVolume;
} else { } else {
// 处理错误 // 处理错误
qDebug() << "Error:" << reply->errorString(); QString errorString = reply->errorString();
qDebug() << "Error:" << errorString;
} }
// 清理资源
reply->deleteLater(); reply->deleteLater();
multiPart->deleteLater();
}); });
} }

View File

@ -9,6 +9,13 @@ namespace Ui {
class CoalStatisticsChartWidget; class CoalStatisticsChartWidget;
} }
enum TimeUnit {
Hour = 0, // 时
Day = 1, // 天
Month = 2, // 月
Year = 3 // 年
};
class CoalStatisticsChartWidget : public QWidget { class CoalStatisticsChartWidget : public QWidget {
Q_OBJECT Q_OBJECT
@ -16,6 +23,13 @@ public:
explicit CoalStatisticsChartWidget(QWidget* parent = nullptr); explicit CoalStatisticsChartWidget(QWidget* parent = nullptr);
~CoalStatisticsChartWidget(); ~CoalStatisticsChartWidget();
private slots:
/**
* @brief on_pushButton_coalStatisOk_clicked
*/
void on_pushButton_coalStatisOk_clicked();
private: private:
/** /**
* @brief initCoalStatisticsBarChart * @brief initCoalStatisticsBarChart
@ -33,7 +47,12 @@ private:
QChart* m_chart; QChart* m_chart;
QChartView* m_chartView; QChartView* m_chartView;
QBarSeries* m_series; QBarSeries* m_series;
QDateTimeAxis* m_axisX;
QValueAxis* m_axisY;
QTimer* m_timer; QTimer* m_timer;
QSettings* m_systemSetting;
}; };
#endif // COALSTATISTICSCHARTWIDGET_H #endif // COALSTATISTICSCHARTWIDGET_H

View File

@ -32,13 +32,13 @@
<item> <item>
<layout class="QHBoxLayout" name="horizontalLayout"> <layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing"> <property name="spacing">
<number>15</number> <number>5</number>
</property> </property>
<property name="leftMargin"> <property name="leftMargin">
<number>10</number> <number>6</number>
</property> </property>
<property name="rightMargin"> <property name="rightMargin">
<number>10</number> <number>6</number>
</property> </property>
<item> <item>
<widget class="QLabel" name="label"> <widget class="QLabel" name="label">
@ -204,6 +204,42 @@ QDateTimeEdit::up-button, QDateTimeEdit::down-button {
</item> </item>
</widget> </widget>
</item> </item>
<item>
<widget class="QPushButton" name="pushButton_coalStatisOk">
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>45</width>
<height>20</height>
</size>
</property>
<property name="styleSheet">
<string notr="true">QPushButton{
border-image: url(:/Resource/image/labelunSelect.png);
color:white;
font-size: 14px;
border: none;
}
QPushButton:hover{
border-image: url(:/Resource/image/labelhover.png);
}
QPushButton:pressed{
border-image: url(:/Resource/image/labelSelect.png);
}
</string>
</property>
<property name="text">
<string>确定</string>
</property>
</widget>
</item>
</layout> </layout>
</item> </item>
<item> <item>