一、定义QObject子类

Myudp.h

#ifndef MYUDP_H
#define MYUDP_H #include <QObject>
#include <QUdpSocket>
class Myudp : public QObject
{
Q_OBJECT
public:
explicit Myudp(QObject *parent = nullptr);
signals:
void rcvdDataSignal(const QByteArray&);
void sendedSignal(const QString&);//发送成功
public slots:
void initUdpSlot();
void requestSlot();
void sendSlot(const QByteArray&);
private:
QUdpSocket* udpClient = nullptr;
const QString localIp="127.0.0.1";
const quint16 localPort=;
const QString aimIp="127.0.0.1";
const quint16 aimPort=;
}; #endif // MYUDP_H

Myudp.cpp

#include "myudp.h"

Myudp::Myudp(QObject *parent) : QObject(parent)
{ } /***********************************************/
// z 函数名称:初始化
// h 函数作用:NULL
// u 函数参数:NULL
// x 函数返回值:NULL
// y 备注:NULL
/***********************************************/
void Myudp::initUdpSlot()
{
if(udpClient == nullptr)
{
udpClient = new QUdpSocket(this);
udpClient->bind(QHostAddress(localIp),localPort);
QObject::connect(udpClient,SIGNAL(readyRead()),this,SLOT(requestSlot()));
}
} /***********************************************/
// z 函数名称:接收数据
// h 函数作用:NULL
// u 函数参数:NULL
// x 函数返回值:NULL
// y 备注:NULL
/***********************************************/
void Myudp::requestSlot()
{
if(udpClient->pendingDatagramSize() == )
{
return;
}
QByteArray ba;
ba.resize(udpClient->pendingDatagramSize());
QHostAddress tempHost("");
quint16 port = ;
udpClient->readDatagram(ba.data(),udpClient->pendingDatagramSize(),&tempHost,&port); emit rcvdDataSignal(ba);
} /**
*函数名:发送槽函数
*函数参数:NULL
*函数作用:NULL
*函数返回值:NULL
*备注:NULL
*/
void Myudp::sendSlot(const QByteArray &info)
{
if(info.size()==udpClient->writeDatagram(info,QHostAddress(aimIp),aimPort))
{
QString str = info.toHex().toUpper();
emit sendedSignal(str);
}
}

二、注册Myudp类,在QML中实例化【注册C++类

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QThread>
#include "myudp.h"
#include <QQuickView>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); qmlRegisterType<Myudp>("Myudp.module",1,0,"Myudp");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -; return app.exec();
}

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2
import Myudp.module 1.0
import QtQuick.Controls 2.2
Window {
id: root
visible: true
width:
height:
title: qsTr("Hello World") Myudp{
id:udp
}
Row{
Button {
id: connetBtn
text: qsTr("连接")
onClicked: {
udp.initUdpSlot()
}
} Button {
id: sendBtn
text: qsTr("发送")
onClicked: {
udp.sendSlot("")
}
}
}
}

三、注册Myudp对象,在QML直接使用【设置上下文属性

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QThread>
#include "myudp.h"
#include <QQuickView>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); Myudp udp; QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("udp",&udp);//注册对象
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -; return app.exec();
}

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
Window {
id: root
visible: true
width:
height:
title: qsTr("Hello World") Row{
Button {
id: connetBtn
text: qsTr("连接")
onClicked: {
udp.initUdpSlot()
}
} Button {
id: sendBtn
text: qsTr("发送")
onClicked: {
udp.sendSlot("")
}
}
}
}

ps:举例使用QTimer

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QThread>
#include "myudp.h"
#include <QQuickView>
#include <QQmlContext>
#include <QTimer>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); qmlRegisterType<QTimer>("QTimer.module",1,0,"Timer"); QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -; return app.exec();
}

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2
import QTimer.module 1.0
import QtQuick.Controls 2.2
Window {
id: root
visible: true
width:
height:
title: qsTr("")
Rectangle {
id: lamp
width:
height:
radius:
color: "red"
anchors.centerIn: parent
}
Timer {
id:countDown
interval:
property bool isChange: true
onTimeout: {
isChange = !isChange
if(isChange){
lamp.color = "black"
}
else{
lamp.color = "red"
}
}
Component.onCompleted: {
countDown.start()
}
}
}

效果:每隔一秒修改背景色

果然采用GPU渲染:

QML使用C++对象的更多相关文章

  1. 在 C++ 中使用 QML 对象

    看过了如何在 QML 中使用 C++ 类型或对象,现在来看如何在 C++ 中使用 QML 对象. 我们可以使用 QML 对象的信号.槽,访问它们的属性,都没有问题,因为很多 QML 对象对应的类型,原 ...

  2. Python操作qml对象

    1. 如何在python里获得qml里的对象? 1.1 获取根对象 QML: import QtQuick 2.12 import QtQuick.Controls 2.12 ApplicationW ...

  3. QML与Qt C++ 交互机制探讨与总结

    介绍 QML和 C++对象可以通过,signals,slots和 属性修改进行交互.对于一个C++对象,任何数据都可以通过Qt的 Meta-Object System暴露给QML(何总方法,后面介绍) ...

  4. QML 从入门到放弃 第二卷

    第二卷如何更快速的放弃,注重的是C++和QML的交互 <1>记事本.. (1) 先测试下不在QML创建C++对象,仅仅在main.cpp添加一个属性函数供调用. 注意只使用槽函数来做到. ...

  5. [转载]震惊!QWidget竟然可以嵌入到QML中,QMl窗口句柄竟然是这样获取

      背景 记得在初学qml时,就被大佬告知Qml的实现有两种方式“view+item”和“engine+widow”,那么能不能将QWidget嵌入到QML中来呢,我收到的答案是不可以,原因是QML的 ...

  6. Qt Quick快速入门之qml与C++交互

    C++中使用qml对象,直接使用findChild获取qml对象,然后调用setProperty方法设置属性,当然必须在加载qml之后才能使用,不然findChild找不到对象,用法如下. engin ...

  7. 深入解析QML引擎, 第3部分: 绑定类型

    原文 QML Engine Internals, Part 3: Binding Types 译者注:这个解析QML引擎的文章共4篇,分析非常透彻,在国内几乎没有找到类似的分析,为了便于国内的QT/Q ...

  8. QML与Qt C++ 交互机制探讨与总结(转)

    原文转自 https://www.cnblogs.com/aoldman/p/4103510.html 介绍 QML和 C++对象可以通过,signals,slots和 属性修改进行交互.对于一个C+ ...

  9. Qt Quick 之 QML 与 C++ 混合编程具体解释

    Qt Quick 技术的引入.使得你能够高速构建 UI ,具有动画.各种绚丽效果的 UI 都不在话下.但它不是万能的.也有非常多局限性,原来 Qt 的一些技术,比方低阶的网络编程如 QTcpSocke ...

随机推荐

  1. 前端知识总结--html

    1.  doctype的作用是什么? <!DOCTYPE> 声明必须是 HTML 文档的第一行,位于 <html> 标签之前. <!DOCTYPE> 声明不是 HT ...

  2. 备份MySQL数据库并上传到阿里云OSS存储

    1. 环境配置 要将本地文件上传到阿里云oss中, 必须使用阿里云提供的工具 ossutil, 有32位,也有64位的, Linux和Windows都有.具体可以到阿里云官网下载 官网及文档: htt ...

  3. c++之:new与malloc

    #include <iostream> using namespace std; void spacealloc_c() { //开辟内存空间---C语言风格 int *p = (int ...

  4. [cf920G][容斥原理+二分]

    https://codeforc.es/contest/920/problem/G G. List Of Integers time limit per test 5 seconds memory l ...

  5. HttpServletRequest获取浏览器、服务端和客户端信息

    如何通过HttpServletRequest来获取到上面的属性呢? 1.引入开源工具 <!-- https://mvnrepository.com/artifact/eu.bitwalker/U ...

  6. Java8实战,

    Supplier 1, @FunctionalInterfacepublic interface Supplier<T> { 2,    T get(); 3, Supplier<A ...

  7. tsnr--基于vpp+dpdk的高性能防火墙

    tsnr--基于vpp+dpdk的高性能防火墙 2019年01月31日 12:06:00 网络安全研发随想 阅读数:508   版权声明:本文为博主原创文章,未经博主允许不得转载. https://b ...

  8. pandas 筛选某一列最大值最小值 sort_values、groupby、max、min

    高效方法: dfs[dfs['delta'].isnull()==False].sort_values(by='delta', ascending=True).groupby('Call_Number ...

  9. 数据结构实验之二叉树六:哈夫曼编码(SDUT 3345)

    题解:离散中的"最小生成树(最优树)". #include <bits/stdc++.h> using namespace std; void qusort(int l ...

  10. c++ 读取文件字符串 并且解析

    /* "/Users/macname/Desktop/aa-1.log" 链接:https://pan.baidu.com/s/1fKB5vXDe6bYOhoslc-kr7w  密 ...