C++自定义信号和QML的槽函数建立连接

0x00 在C++代码在定义一个信号函数:“void sendData2UI(QString msg);”,该函数主要是将接收到的UDP消息发送到QML界面中

#ifndef UDPCLI_H
#define UDPCLI_H

#include 
#include 
#include 

class UdpCli : public QObject
{
    Q_OBJECT
public:
    explicit UdpCli(QObject *parent = nullptr);

    Q_INVOKABLE void sendMsg(QString msg);
    void recvMsg();

signals:
    void sendData2UI(QString msg);

private:
    QUdpSocket* udpSocket;
};

#endif // UDPCLI_H


#include "udpcli.h"
#include 

UdpCli::UdpCli(QObject *parent) : QObject(parent)
{
    udpSocket = new QUdpSocket(this);
    udpSocket->bind(QHostAddress::LocalHost, 9898);

    connect(udpSocket, &QUdpSocket::readyRead, this, &UdpCli::recvMsg);
}

void UdpCli::sendMsg(QString msg)
{
    udpSocket->writeDatagram(msg.toStdString().c_str(), msg.size(),
                             QHostAddress("127.0.01"), 19898);
}

void UdpCli::recvMsg()
{
    QHostAddress sender;
    quint16 senderPort;

    while (udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());

        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        QString msg = QString::fromLocal8Bit(datagram);
        qDebug() << msg;

        sendData2UI("Recv[" + sender.toString() + ":" + QString::number(senderPort) + "] " + msg);
    }
}

0x01 在QML代码中使用Connections创建C++对象的信号与QML中定义的槽函数连接

import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 1.4
import QtQuick.Controls 2.12 as Controls
import QtQuick.Controls.Styles 1.4
import QtQuick.Controls.Material 2.12
// import com.HLD 1.0
import QtQml 2.14

Window {
    visible: true;
    minimumHeight: 480;
    maximumHeight: 480;
    minimumWidth: 640;
    maximumWidth: 640;
    title: qsTr("HLD.TableView")
    color: Qt.rgba(127, 255, 170, 1.0)

    Column{
        anchors.centerIn: parent;
        spacing: 10;

        Row{
            id: sendArea;
            spacing: 10;

            TextField {
                id: inputField;
                width: 300;
                placeholderText: "Enter text";

                style: TextFieldStyle {
                    background: Rectangle {
                        color: "#ffffff"
                        border.color: "#40E0D0"
                        radius: 4
                    }
                }
            }

            Button{
                id: btn;

                text: "发送";
                style: ButtonStyle {
                    background: Rectangle {
                        color: "#2196f3"
                        radius: 4;
                    }

                    label: Text {
                        text: btn.text
                        color: "#ffffff"
                        font.pixelSize: 16
                    }
                }

                onClicked: {
                    if(inputField.text.length > 0)
                    {
                        console.log(inputField.text);
                        UdpCli.sendMsg(inputField.text);
                    }
                }
            }
        }

        Text {
            text: qsTr("接收数据:");
        }

        TextArea{
            id: recvMsg;
            width: sendArea.width;
            readOnly: true;
        }

        Connections{
            target: UdpCli;
            function onSendData2UI(msg){
                recvMsg.text += msg;
                recvMsg.text += "\r\n";

                console.log(msg);
            }
        }
    }
}
#include 
#include 
#include 
#include 
#include 
#include "udpcli.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    QQuickStyle::setStyle("Material");

    UdpCli m_udpCli;

    /**
     * @brief qmlRegisterSingletonInstance
     * @param Url名
     * @param 主版本
     * @param 次版本
     * @param Qml中控件名
     * @param C++对象
     */
    // qmlRegisterSingletonInstance("com.HLD", 1, 0, "UdpCli", &m_udpCli);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);

    auto context = engine.rootContext();
    context->setContextProperty("UdpCli", &m_udpCli);

    engine.load(url);

    return app.exec();
}

效果演示:

C++自定义信号和QML的槽函数建立连接_第1张图片

你可能感兴趣的:(QML,c++,QML)