一、定义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文本获取图片Url,判断图片大小,存数据库

    1.从html文本获取图片Url /** * html文本中取出url链接 */ public class Url { public static void main(String[] args) { ...

  2. Git---报错:git Please move or remove them before you can merge 解决方案

    场景: 当前在本地仓库lucky,因修改了123.txt的文件内容,需要将lucky分支push到远程Git库,在push前有其他的同事已删除了远程Git库中的123.txt文件.因此这时就产生了远程 ...

  3. 获取历史K线数据的几个方法

    1.通过已有的股票交易软件下载数据,如果他们是开源结构的,就可以解析他们的K线数据. 2.在互联网上抓取数据 int iStockCode;CString strUrl; 通过OpenUrl.Read ...

  4. 使用openoffice转pdf,详细

    期由于项目的需求,需要word文档转pdf在线预览,由于一直没有接触这块,所以花了将近四天时间才弄明白. 写这篇文章的主要目的是加深自己的记忆,同时方便以后在用. (最近有使用了这个功能,发现这篇文章 ...

  5. sql server newid() 的用法

    sql newid()随机函数   从A表随机取2条记录,用SELECT TOP 10 * FROM ywle order by newid()order by 一般是根据某一字段排序,newid() ...

  6. 异常:ORA-01013: 用户请求取消当前的操作

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/bnmnba/article/detail ...

  7. springboot使用rabbitmq-Topic模式,亲自实测能用!!!

    0.项目目录截图 ===================================================================== springboot的版本: <gr ...

  8. learning scala implicit class

    隐式类可以用来扩展对象的功能非常方便 example: object ImplicitClass_Tutorial extends App { println("Step 1: How to ...

  9. P5431 【模板】乘法逆元2

    洛谷题目链接 刚开始做乘法逆元还是有点懵逼的~ 以下式子都在模\(p\)意义下进行 我们把式子改一下,变成:\[\sum\limits_{i=1}^nk^i\times a_i^{-1}\] 我们先算 ...

  10. Selenium操作Chrome模拟手机浏览器

    目录 使用指定设备 使用自定义设备 在使用Chrome浏览网页时,我们可以使用Chrome开发者工具模拟手机浏览器,在使用Selenium操作Chrome时同样也可以模拟手机浏览器.主要有以下两种用途 ...