send data from QUDPsocket c++ to QML UI fail
Unsolved
QML and Qt Quick
-
i try send data from UDPsocket to QMl with timer 1s but it not working.
udp.h#ifndef UDP_H #define UDP_H #include <QObject> #include <QUdpSocket> class UDP : public QObject { Q_OBJECT Q_PROPERTY(QString convert READ receiverdata); public: explicit UDP(QObject *parent = nullptr); QString convert; signals: public slots: QString receiverdata(); private: QUdpSocket *socket; }; #endif // UDP_H
udp.cpp
#include "udp.h" #include <iostream> UDP::UDP(QObject *parent) : QObject{parent} { socket = new QUdpSocket(this); socket->bind(QHostAddress::AnyIPv4,5005); connect(socket,SIGNAL(readyRead()),this,SLOT(receiverdata())); } QString UDP::receiverdata() { QByteArray Buffer; Buffer.resize(socket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; socket->readDatagram(Buffer.data(),Buffer.size(),&sender,&senderPort); qDebug() << "message: "<< QString(Buffer); convert = QString(Buffer); return convert; }
main.cpp
#include <QGuiApplication> #include <QQmlApplicationEngine> #include "someclass.h" #include <QQmlContext> #include "udp.h" int main(int argc, char *argv[]) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QGuiApplication app(argc, argv); UDP server; QString convert; convert = server.receiverdata(); 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); engine.load(url); QQmlContext * rootContext = engine.rootContext(); rootContext -> setContextProperty("UDP",&server); return app.exec(); }
main.qml
import QtQuick 2.15 import QtQuick.Window 2.15 import QtQuick.Controls 2.15 Window { width: 640 height: 480 visible: true title: qsTr("Hello World") Text { id: text1 text: qsTr("text") } Timer{ interval: 1000 running: true repeat: true onTriggered: text1.text = UDP.receiverdata(); } }
Application output:
message: ""
message: "30"
message: ""
message: "26"
message: ""
message: "29"
message: ""
message: "68"
message: ""
message: "36"
message: ""
message: "13"
message: ""
message: "78"when timer run, message will be "". i don't understand it.
pl help me, thank you.