0x00 使用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
Window {
visible: true;
minimumHeight: 480;
maximumHeight: 480;
minimumWidth: 640;
maximumWidth: 640;
title: qsTr("HLD.TableView")
color: Qt.rgba(127, 255, 170, 1.0)
Row{
anchors.centerIn: parent;
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);
}
}
}
}
}
0x01 使用C++定义一个类,并用Q_INVOKABLE宏修饰一个发送UDP消息的成员函数。
#ifndef UDPCLI_H
#define UDPCLI_H
#include <QObject>
#include <QUdpSocket>
#include <QString>
class UdpCli : public QObject
{
Q_OBJECT
public:
explicit UdpCli(QObject *parent = nullptr);
Q_INVOKABLE void sendMsg(QString msg);
signals:
private:
QUdpSocket* udpSocket;
};
#endif // UDPCLI_H
//----------------------------
#include "udpcli.h"
#include <QHostAddress>
UdpCli::UdpCli(QObject *parent) : QObject(parent)
{
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::LocalHost, 9898);
}
void UdpCli::sendMsg(QString msg)
{
udpSocket->writeDatagram(msg.toStdString().c_str(),msg.size(),
QHostAddress("127.0.01"), 19898);
}
将C++对象注册成QML控件
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickStyle>
#include <QMetaObject>
#include <QQmlContext>
#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();
}
- 效果演示