QT QML初体验随笔之QQuickView(9)

来源:互联网 发布:google seo 编辑:程序博客网 时间:2024/05/16 08:00

real类型浮点数如何截取小数位以及与C++混编

1.背景


QT QML初体验随笔之QQuickView(8)以及QT Tcp客户端发送接收并存初体验随笔


2.混编:对Tcp客户端进行修改

添加到元对象系统中才能够被QML所调用,所以重点为Q_INVOKABLE(混编的部分使用方法)

#ifndef TCPCLIENT_H#define TCPCLIENT_H#include <QObject>class QTcpSocket;class TcpClient : public QObject{Q_OBJECTpublic:TcpClient(QObject *parent = 0);~TcpClient();    Q_INVOKABLE bool connectToHost(QString strIP, quint16 port);    Q_INVOKABLE void send(const quint64& sendDatLen, const unsigned int& cnt);    Q_INVOKABLE bool disconnect();    Q_INVOKABLE qint64 getSendTotalLen();    Q_INVOKABLE qint64 getRecvTotalLen();    private:    QTcpSocket* m_pClient;    QByteArray m_sendDat;    bool m_bConnect;    qint64 m_bytesRead;    qint64 m_totalBytes;    qint64 m_bytesToWrite;    qint64 m_bytesWritten;private:QByteArray increasingSequence(const quint64& sendDatLen); signals:void error(int socketError, const QString &message);private slots:void recvSlot();void sendSlot(qint64 numBytes);};#endif // TCPCLIENT_H

#include "tcpclient.h"#include <QTcpSocket>#include <QDebug>#include <QByteArray>#include <QTimer>#include <QtTest/QTest>TcpClient::TcpClient(QObject *parent)    : QObject(parent),m_pClient(nullptr),m_bConnect(false),m_totalBytes(0),m_bytesToWrite(0),m_bytesWritten(0),    m_bytesRead(0){m_sendDat.clear();m_pClient = new QTcpSocket(this);if (m_pClient){connect(m_pClient, SIGNAL(readyRead()), this, SLOT(recvSlot()));connect(m_pClient, SIGNAL(bytesWritten(qint64)), this, SLOT(sendSlot(qint64)));}}TcpClient::~TcpClient(){}bool TcpClient::connectToHost(QString strIP, quint16 port){m_pClient->abort();m_pClient->connectToHost(strIP, port);const int timeOut = 5 * 1000;if (!m_pClient->waitForConnected(timeOut)){emit error(m_pClient->error(), m_pClient->errorString());m_bConnect = false;}else{m_bConnect = true;}return m_bConnect;}void TcpClient::send(const quint64& sendDatLen, const unsigned int& cnt){if (m_bConnect){m_sendDat = increasingSequence(sendDatLen);m_totalBytes = sendDatLen*cnt;m_bytesToWrite = m_totalBytes - m_pClient->write(m_sendDat);}}QByteArray TcpClient::increasingSequence(const quint64& sendDatLen){QByteArray tmp;unsigned char cnt = 0x0;while (tmp.length() < sendDatLen){tmp.append(cnt++);}return tmp;}void TcpClient::recvSlot(){QByteArray dat = m_pClient->readAll();m_bytesRead += dat.length();}void TcpClient::sendSlot(qint64 numBytes){m_bytesWritten += numBytes;if (m_bytesToWrite > 0){m_bytesToWrite -= m_pClient->write(m_sendDat);}else{if (m_bytesWritten == m_totalBytes){}}}bool TcpClient::disconnect(){bool bFlag = true;if (m_pClient){m_pClient->disconnectFromHost();        //m_pClient->waitForDisconnected(1000);if ((m_pClient->state() == QAbstractSocket::UnconnectedState || m_pClient->waitForDisconnected(1000))){bFlag = true;}else{bFlag = false;}}return bFlag;}qint64 TcpClient::getSendTotalLen(){    return m_bytesWritten;}qint64 TcpClient::getRecvTotalLen(){    return m_bytesRead;}

main.cpp作为QML属性调用,还有一种作为QML的元素调用自行查阅

#include <QApplication>#include <QQmlContext>#include <QQuickView>// 注册QML#include "Tcp/tcpclient.h"//#include <QtQml>int main(int argc, char *argv[]){    QApplication app(argc, argv);    // 注册//    qmlRegisterType<TcpClient>("qt.Kingmei.Tcp", 1, 0, "TcpClient");    QQuickView viewer;    viewer.rootContext()->setContextProperty("wndCtrl", &viewer);    viewer.rootContext()->setContextProperty("tcpClient", new TcpClient);  // 添加为QML属性    viewer.setResizeMode(QQuickView::SizeRootObjectToView);    viewer.setFlags(Qt::Window| Qt::FramelessWindowHint);    viewer.setSource(QUrl("../TcpTestV/main.qml"));    viewer.show();    return app.exec();}


3.QT QML初体验随笔之QQuickView(8)基础上简单的测试接收网路数据速率

main.qml修改添加

mport QtQuick 2.4import QtQuick.Controls 1.2import QtQuick.Controls.Styles 1.2import "QML_Kingmei/Base_1"import "QML_Kingmei/Base"// C++与QML混编//import qt.Kingmei.Tcp 1.0Rectangle{    id: mainWnd;    // 尺寸    height: 600;    width: 960;    // 颜色    color: "green";    // 边界    border.width: 2;    border.color: "#ff808080";//    border.color: "#ffc0c0c0";//    radius: 10;    opacity: 1;        // 区分颜色透明度和窗口透明度    // 背景    Image {        id: skinBackGround;     // 内部调用对象名称        // 显示mainWnd的边框        height: parent.height - parent.border.width*2;        width: parent.width - parent.border.width*2;        anchors.centerIn: parent;        // image源        source: "Image/background_mainwnd.jpg";        // mainWnd可以拖动        MouseArea {            anchors.fill: parent            property variant previousPosition            onPressed: {                previousPosition = Qt.point(mouseX, mouseY)            }            onPositionChanged: {                if (pressedButtons == Qt.LeftButton) {                    var dx = mouseX - previousPosition.x;                    var dy = mouseY - previousPosition.y;                    wndCtrl.x += dx;                    wndCtrl.y += dy;                }            }        }        // 标题        Label_Kingmei {            id: title;      // 内部调用对象名称            y: 8;            x: 8;            color: "#ff000000";            text: "NetCtrlV";            font.pixelSize: 20;            onLinkActivated: {                Qt.openUrlExternally(link);            }        }        // 状态栏        Label_Kingmei {            id: stateBar;            anchors.bottomMargin: 4;            anchors.rightMargin: 8;            anchors.right: parent.right;            anchors.bottom: parent.bottom;            text: 'by <a href="http://blog.csdn.net/kingmei130283">kingmei</a>';            font.pixelSize: 20;            onLinkActivated: {                Qt.openUrlExternally(link);            }        }        NetCtrl_Kingmei {            id: netCtrl;            anchors.top: title.bottom;            x: 8;            property bool bConnect: true;            onClicked: {// 混编-修改网络控件按下处理内容                indicatorState = indicatorWait;                if(bConnect)                {                    if(tcpClient.connectToHost(ip, port))                    {                        indicatorState = indicatorCorrect;                        setEnabled(false);                        bConnect = false;                        mainWnd.recvTotalLen = 0;                        mainWnd.recvLenTmp = 0;                        mainWnd.recvCnt = 0;                        secondCnt.start();                    }                    else                    {                        indicatorState = indicatorError;                        setEnabled(true);                    }                }                else                {                    if(tcpClient.disconnect())                    {                        indicatorState = indicatorNormal;                        setEnabled(true);                        bConnect = true;                        secondCnt.stop();                    }                    else                    {                        indicatorState = indicatorError;                    }                }            }        }        // 系统按钮        SysBtns_Kingmei {            id: sysBtns;            y: sysBtns.anchors.rightMargin - 4;            anchors.right: parent.right;            // 槽            onMin: {               wndCtrl.showMinimized();            }            onClose: {               wndCtrl.close();            }        }    }    LcdNumber_Kingmei {        id: recvDatV;        anchors.centerIn: parent;        input: 0;        font.pixelSize: 60;//        color: "red";    }    Connections {        target: tcpClient;        onError: {            console.log("error:", socketError, message);        }    }    // 混编-添加接收变量属性以及1s定时显示    property int recvTotalLen: 0;    property int recvLenTmp: 0;    property int recvCnt: 0;    Timer {        id: secondCnt;        // 周期时间设定        interval: 1000;        // 周期触发,还是一次触发        repeat: true;        // 立刻触发一次        triggeredOnStart: true;        onTriggered: {            parent.recvTotalLen = tcpClient.getRecvTotalLen();            if(parent.recvLenTmp != parent.recvTotalLen)            {                ++parent.recvCnt;                parent.recvLenTmp = parent.recvTotalLen;                test.input = (parent.recvLenTmp*1.0/1024/1024/parent.recvCnt).toFixed(2);   // real 截取小数位            }            else            {                parent.recvLenTmp = 0;                parent.recvTotalLen = 0;                parent.recvCnt = 0;            }        }    }}

4.终于迈出第一步不再是单纯的QML界面,而是有部分功能软件

5.总结

  • 如何截取real浮点类型的小数位,Qt中查不到,原来是JavaScript的方法