Qt gas safety management system to write data to print 11-

I. Introduction

In a variety of software systems, data printing is one of the commonly used functions, data query results in general will be exported to excel, but also print directly on the data results of a query, the printer offers class QPrinter in Qt, the printsupport component, text can be passed QTextDocument, then call the print method QTextDocument to print data, QTextDocument supports text html format, so scalability is very big, and we know the table border color, etc., can all be used html the syntax to represent, but looks like not a lot of support for html content, only partially, also support some style, but also has enough, commonly used forms, borders, colors, margins, fonts, etc., are in place, it would be ok.

Export data in the previous article xml format data usage, and export pdf print is a print class used in the document to pdf, html format is the data used in the same token, the print data is in this format, and the only difference is exported to pdf export to pdf is to set the output format is PDF, printer.setOutputFormat (QPrinter :: PdfFormat); then set the output file save location printer.setOutputFileName (fileName); in fact, the content is exactly the same organization, it is said the new version the qt package intended QtPdf a separate module, do not know the next version will not be released, so that you can edit pdf files across operating platforms of.

Skin Open Source: https://gitee.com/feiyangqingyun/QWidgetDemo https://github.com/feiyangqingyun/QWidgetDemo
File name: styledemo

Experience Address: https://gitee.com/feiyangqingyun/QWidgetExe https://github.com/feiyangqingyun/QWidgetExe
File name: bin_sams.zip

Second, the functional characteristics

  1. Collect data port, serial port support + network port, serial port supports baud rate set free + serial number, network support freely set the IP address + communication ports, each port supports acquisition cycle, default 1 second address, set the communication timeout support frequency default 3 times, support the largest reconnection time for the re-read off-line equipment.
  2. Controller information, the controller can be added to the name, address + control model selection controller, the controller is provided below the number of detectors.
  3. Probe information, the bit number can be added, can be freely selected probe type, gas type, gas symbol, the value of the high alarm, low reported values, buffer values, a value is cleared, if enabled, an alarm sound, a background map, the storage period, the value conversion of decimal places, the alarm delay time, alarm type (HH, LL, HL) and the like.
  4. Detector Model Controller Model + + + gas symbol gas species, can be freely arranged.
  5. Map supports importing and delete all the corresponding map position detector can freely drag saved.
  6. Port information + + probe information controller information, import and export support + + print exported to Excel.
  7. + + Alarm log record recording the user, the query condition combination to support multiple, such as + period + Controller detectors, all record print support exported to Excel +.
  8. Export to excel record of support for all forms such as excel + wps file versions, does not rely on software such as excel.
  9. You can delete data within a specified time frame, auto clean up early data, set the maximum number of record-keeping.
  10. Support forwarding alarm messages, the plurality of support receiving phone number, the transmission interval can be set, such as instant or the transmission 6 hours send all the alarm messages, message content is too long, a number of messages automatically split.
  11. Support alarm mail forwarding, support for receiving a plurality of mailboxes, the transmission interval can be set, such as instant transmission or six hours all the alarm information once transmitted, to support attachments.
  12. High + Low message packets Color Color values ​​Color + + + 0 normal color profile curves + background color, etc., can be freely selected.
  13. Software English title Chinese title + + + logo Copyright paths can be freely set.
  14. Provides switch switched on the alarm sound + + + automatic login remember passwords.
  15. Sound the alarm can be set to play frequency interface available in 17 skin file selection.
  16. Support cloud data synchronization, cloud database information can be set, such as database name, username + password.
  17. Support network forwarding and receiving network, the network is open to receive, parse udp software to receive data from. Network forwarding support multiple target IP, thus achieving a local collection of software, free data to the client, at any time to view the detector data.
  18. Automatically remembers the last stop of the user interface + additional information, automatic application restart.
  19. Alarm automatically switches to a map corresponding to the detector button flashes.
  20. Double-click the probe icon, you can back control.
  21. Support user rights management, administrators + operator into two categories, user login + user exits, you can remember the password and automatic login, more than three times error prompt and close the program.
  22. Supports four monitoring mode, the monitoring device panel monitor + Map + table + curve data monitoring data monitoring, are free to switch the four synchronization application.
  23. Support alarm relay linkage, a bit serial number can be linked across a plurality of modules and a relay number, support-many.
  24. Local data storage support sqlite + mysql, supports remote data synchronization to the cloud database. Automatic reconnection.
  25. Real-time local device collected data uploaded to the cloud, so that the phone APP or web and other ways to extract.
  26. Supports two data sources, one serial port and the data acquisition devices through a network protocol, one is the collection database. Acquisition mode database can be used as a general system.
  27. Carrying equipment simulation tools, devices 16 support analog data, but also with the database data simulation, when there is no data to test the device.
  28. Default communication protocol using modbus protocol, later adding support mqtt and other things of the agreement, made common system.
  29. Supports all windows operating system + linux operating system and other operating systems.

Third, renderings

Fourth, the core code

#include "printapi.h"
#include "qmutex.h"
#include "qprintpreviewdialog.h"
#include "qtextdocument.h"
#include "qtextobject.h"

QScopedPointer<PrintAPI> PrintAPI::self;
PrintAPI *PrintAPI::Instance()
{
    if (self.isNull()) {
        static QMutex mutex;
        QMutexLocker locker(&mutex);
        if (self.isNull()) {
            self.reset(new PrintAPI);
        }
    }

    return self.data();
}

PrintAPI::PrintAPI(QObject *parent) : QObject(parent)
{
}

void PrintAPI::print(const QString &title, const QString &subTitle, const QList<QString> &columnNames,
                     const QList<int> &columnWidths, const QStringList &content, bool landscape, bool check,
                     int checkColumn, const QString &checkType, const QString &checkValue, const QPrinter::PageSize &pageSize)
{
    //计算行数列数
    int columnCount = columnNames.count();
    int rowCount = content.count();

    //清空原有数据,确保每次都是新的数据
    html.clear();

    //表格开始
    html.append("<table border='0.5' cellspacing='0' cellpadding='3'>");

    //标题占一行,居中显示
    if (title.length() > 0) {
        html.append(QString("<tr><td align='center' style='vertical-align:middle;font-weight:bold;' colspan='%1'>").arg(columnCount));
        html.append(title);
        html.append("</td></tr>");
    }

    //副标题占一行,左对齐显示
    if (subTitle.length() > 0) {
        html.append(QString("<tr><td align='left' style='vertical-align:middle;' colspan='%1'>").arg(columnCount));
        html.append(subTitle);
        html.append("</td></tr>");
    }

    //循环写入字段名,字段名占一行,居中显示
    if (columnCount > 0) {
        html.append("<tr>");

        for (int i = 0; i < columnCount; i++) {
            html.append(QString("<td width='%1' bgcolor='lightgray' align='center' style='vertical-align:middle;'>").arg(columnWidths.at(i)));
            html.append(columnNames.at(i));
            html.append("</td>");
        }

        html.append("</tr>");
    }

    //循环一行行构建数据
    for (int i = 0; i < rowCount; i++) {
        QStringList value = content.at(i).split(";");
        html.append("<tr>");

        //过滤内容,如果启用了过滤数据,则将符合条件的数据突出颜色显示
        bool existCheck = false;

        if (check) {
            if (checkType == "==") {
                if (value.at(checkColumn) == checkValue) {
                    existCheck = true;
                }
            } else if (checkType == ">") {
                if (value.at(checkColumn) > checkValue) {
                    existCheck = true;
                }
            } else if (checkType == ">=") {
                if (value.at(checkColumn) >= checkValue) {
                    existCheck = true;
                }
            } else if (checkType == "<") {
                if (value.at(checkColumn) < checkValue) {
                    existCheck = true;
                }
            } else if (checkType == "<=") {
                if (value.at(checkColumn) <= checkValue) {
                    existCheck = true;
                }
            } else if (checkType == "!=") {
                if (value.at(checkColumn) != checkValue) {
                    existCheck = true;
                }
            }
        }

        if (existCheck) {
            for (int j = 0; j < columnCount; j++) {
                html.append(QString("<td width='%1' align='center' style='vertical-align:middle;'><font color='red'>").arg(columnWidths.at(j)));
                html.append(value.at(j));
                html.append("</font></td>");
            }
        } else {
            for (int j = 0; j < columnCount; j++) {
                html.append(QString("<td width='%1' align='center' style='vertical-align:middle;'>").arg(columnWidths.at(j)));
                html.append(value.at(j));
                html.append("</td>");
            }
        }

        html.append("</tr>");
    }

    html.append("</table>");

    //调用打印机打印
    QPrinter printer;
    //设置输出格式
    printer.setOutputFormat(QPrinter::NativeFormat);
    //设置纸张规格
    printer.setPageSize(pageSize);

    //设置横向纵向及页边距
    if (landscape) {
        printer.setOrientation(QPrinter::Landscape);
        printer.setPageMargins(10, 10, 10, 10, QPrinter::Millimeter);
    } else {
        printer.setOrientation(QPrinter::Portrait);
        printer.setPageMargins(10, 10, 10, 11, QPrinter::Millimeter);
    }

    QPrintPreviewDialog preview(&printer);
    preview.setStyleSheet("QToolButton{background:none;margin:2px;padding:0px;border-width:0px;border-radius:0px;}QLineEdit{border-width:0px;}");
    preview.setWindowTitle("打印预览");
    preview.setWindowFlags(Qt::WindowStaysOnTopHint);
    connect(&preview, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printView(QPrinter *)));
    preview.showMaximized();
    preview.exec();
}

void PrintAPI::print(const QString &title, const QList<QString> &columnNames, const QList<int> &columnWidths,
                     const QStringList &subTitle1, const QStringList &subTitle2,
                     const QStringList &content, bool landscape, bool check,
                     int checkColumn, const QString &checkType, const QString &checkValue, const QPrinter::PageSize &pageSize)
{
    //计算列数
    int columnCount = columnNames.count();

    //清空原有数据,确保每次都是新的数据
    html.clear();

    //表格开始
    html.append("<table border='0.5' cellspacing='0' cellpadding='3'>");

    //标题占一行,居中显示
    if (title.length() > 0) {
        html.append(QString("<tr><td align='center' style='vertical-align:middle;font-weight:bold;' colspan='%1'>")
                    .arg(columnCount));
        html.append(title);
        html.append("</td></tr>");
    }

    //循环添加副标题/字段名/内容
    int count = content.count();

    for (int i = 0; i < count; i++) {
        //加个空行隔开
        html.append(QString("<tr><td colspan='%1'>").arg(columnCount));
        html.append("</td></tr>");

        //副标题1
        if (subTitle1.count() > 0 && subTitle1.count() > i) {
            if (subTitle1.at(i).length() > 0) {
                html.append(QString("<tr><td align='left' style='vertical-align:middle;' colspan='%1'>")
                            .arg(columnCount));
                html.append(subTitle1.at(i));
                html.append("</td></tr>");
            }
        }

        //副标题2
        if (subTitle2.count() > 0 && subTitle2.count() > i) {
            if (subTitle2.at(i).length() > 0) {
                html.append(QString("<tr><td align='left' style='vertical-align:middle;' colspan='%1'>")
                            .arg(columnCount));
                html.append(subTitle2.at(i));
                html.append("</td></tr>");
            }
        }

        //逐个添加字段名称
        if (columnCount > 0) {
            html.append("<tr>");

            for (int i = 0; i < columnCount; i++) {
                html.append(QString("<td width='%1' bgcolor='lightgray' align='center' style='vertical-align:middle;'>")
                            .arg(columnWidths.at(i)));
                html.append(columnNames.at(i));
                html.append("</td>");
            }

            html.append("</tr>");
        }

        QStringList list = content.at(i).split(";");

        //逐个添加数据
        int rowCount = list.count();

        for (int j = 0; j < rowCount; j++) {
            html.append("<tr>");

            QString temp = list.at(j);
            QStringList value = temp.split("|");
            int valueCount = value.count();

            //过滤内容,如果启用了过滤数据,则将符合条件的数据突出颜色显示
            bool existCheck = false;

            if (check) {
                if (checkType == "==") {
                    if (value.at(checkColumn) == checkValue) {
                        existCheck = true;
                    }
                } else if (checkType == ">") {
                    if (value.at(checkColumn) > checkValue) {
                        existCheck = true;
                    }
                } else if (checkType == ">=") {
                    if (value.at(checkColumn) >= checkValue) {
                        existCheck = true;
                    }
                } else if (checkType == "<") {
                    if (value.at(checkColumn) < checkValue) {
                        existCheck = true;
                    }
                } else if (checkType == "<=") {
                    if (value.at(checkColumn) <= checkValue) {
                        existCheck = true;
                    }
                } else if (checkType == "!=") {
                    if (value.at(checkColumn) != checkValue) {
                        existCheck = true;
                    }
                }
            }

            if (existCheck) {
                for (int k = 0; k < valueCount - 1; k++) {
                    html.append(QString("<td width='%1' align='center' style='vertical-align:middle;'><font color='red'>").arg(columnWidths.at(k)));
                    html.append(value.at(k));
                    html.append("</font></td>");
                }
            } else {
                for (int k = 0; k < valueCount; k++) {
                    html.append(QString("<td width='%1' align='center' style='vertical-align:middle;'>").arg(columnWidths.at(k)));
                    html.append(value.at(k));
                    html.append("</td>");
                }
            }

            html.append("</tr>");
        }
    }

    html.append("</table>");

    //调用打印机打印
    QPrinter printer;
    //设置输出格式
    printer.setOutputFormat(QPrinter::NativeFormat);
    //设置纸张规格
    printer.setPageSize(pageSize);

    //设置横向纵向及页边距
    if (landscape) {
        printer.setOrientation(QPrinter::Landscape);
        printer.setPageMargins(10, 10, 10, 10, QPrinter::Millimeter);
    } else {
        printer.setOrientation(QPrinter::Portrait);
        printer.setPageMargins(10, 10, 10, 11, QPrinter::Millimeter);
    }

    QPrintPreviewDialog preview(&printer);
    preview.setStyleSheet("QToolButton{background:none;margin:2px;padding:0px;border-width:0px;border-radius:0px;}QLineEdit{border-width:0px;}");
    preview.setWindowTitle("打印预览");
    preview.setWindowFlags(Qt::WindowStaysOnTopHint);
    connect(&preview, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printView(QPrinter *)));
    preview.showMaximized();
    preview.exec();
}

void PrintAPI::printView(QPrinter *printer)
{
    QTextDocument textDocument;
    textDocument.setHtml(html.join(""));
    textDocument.setPageSize(printer->pageRect().size());
    textDocument.print(printer);
}

Guess you like

Origin www.cnblogs.com/feiyangqingyun/p/11888501.html