qml与C++的交互

qml端使用C++对象类型、qml端调用C++函数/c++端调用qml端函数、qml端发信号-连接C++端槽函数、C++端发信号-连接qml端函数等。

代码资源下载:
https://download.csdn.net/download/TianYanRen111/88779433
若无法下载,直接拷贝以下代码测试即可。

main.cpp

cpp 复制代码
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "MyObject.h"
#include "TestObject.h"

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

    QGuiApplication app(argc, argv);

    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);


    qmlRegisterType<MyObject>("com.mycompany.qmlcomponents", 1, 0, "MyObject");
    qmlRegisterType<TestObject>("com.mycompany.qmlcomponents", 1, 0, "TestObject");

    engine.load(url);

    //
    auto objs = engine.rootObjects();
    auto window = objs.first();

    // c++ 绑定信号槽,C++端发信号
    // 此种形式必须将信号设置为 QVariant类型
    MyObject obj;
    QObject::connect(&obj, SIGNAL(sendCpp2(QVariant, QVariant)), window, SLOT(slotCpp(QVariant, QVariant)));
    obj.test2(); // 发送信号

    // c++端调用qml端函数
    qDebug()<<objs.first()->objectName();
    QVariant ret;
    QVariant arg1 = 123333;
    QVariant arg2 = "zhangsan===";
    QMetaObject::invokeMethod(window, "qmlFunc", Q_RETURN_ARG(QVariant, ret)
                              ,Q_ARG(QVariant, arg1)
                              ,Q_ARG(QVariant, arg2));

    return app.exec();
}

MyObject.h

cpp 复制代码
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include <QObject>
#include <QDebug>

class MyObject : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int num READ num WRITE setNum NOTIFY numChanged)
    Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)

public:
    explicit MyObject(QObject *parent = nullptr);    
    int num() const;
    QString name() const;

    Q_INVOKABLE void printMessage();
    Q_INVOKABLE void test1() {
        emit sendCpp1("--------------111111-------");
    }
    void test2() {
        emit sendCpp2("---------2222222222------------series", 222222222222);
    }

public slots:
    void setNum(int num);
    void setName(QString name);

    void onMsg(QString msg, int value);

signals:
    void numChanged(int num);
    void nameChanged(QString name);

    void sendCpp1(QString message);
    void sendCpp2(QVariant message, QVariant value);

private:
    int m_num;
    QString m_name;
};

#endif // MYOBJECT_H

MyObject.cpp

cpp 复制代码
#include "MyObject.h"

MyObject::MyObject(QObject *parent) : QObject(parent)
{

}

int MyObject::num() const
{
    return m_num;
}

QString MyObject::name() const
{
    return m_name;
}

void MyObject::printMessage()
{
    qDebug() << "@@@@@@@@@@@@@@@ message is:> 11111111111";
}

void MyObject::setNum(int num)
{
    if (m_num == num)
        return;

    m_num = num;
    emit numChanged(m_num);
}

void MyObject::setName(QString name)
{
    if (m_name == name)
        return;

    m_name = name;
    emit nameChanged(m_name);
}

void MyObject::onMsg(QString msg, int value)
{
    qDebug() << "################> msg:value is:> " << msg << value;
}

TestObject.h

cpp 复制代码
#ifndef TESTOBJECT_H
#define TESTOBJECT_H

#include <QObject>

class TestObject : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString message READ message WRITE setMessage NOTIFY messageChanged)

public:
    explicit TestObject(QObject *parent = nullptr);
    QString message() const {
        return m_message;
    }

public slots:
    void setMessage(QString message) {
        {
            if (m_message == message)
                return;

            m_message = message;
            emit messageChanged(m_message);
        }

    }

signals:
    void messageChanged(QString message);

private:
    QString m_messsage;
    QString m_message;
};

#endif // TESTOBJECT_H

main.qml

css 复制代码
import QtQuick 2.0
import QtQuick.Controls 2.12
import QtQuick.Window 2.12
import QtQuick.Layouts 1.3
import QtQml 2.12
import com.mycompany.qmlcomponents 1.0

Window {
    id: window
    objectName: "myWindow"
    visible: true
    width: 600
    height: 250
    title: qsTr("Hello World")

    signal sendMsg(string msg, int value)

    function slotCpp(message, value) {
        console.log(">>>... " + message + " " + value)
    }

    function qmlFunc(msg, value) {
        console.log("......qml function... msg:value:> ", msg, value)
    }

    MyObject {
        id: myObject
        num: 101
        name: "zhangSan"

        onNumChanged: {
            console.log("...new num is:> ", num)
        }

        onNameChanged: {
            console.log("...new name is:> ", name)
        }

        Component.onCompleted: {
            console.log("...init num and name is:> " + num + " " + name)
        }
    }

    TestObject {
        id: testObject
        message: "HelloWorld..."

        onMessageChanged: {
            console.log("...new message is:> ", message)
        }

        Component.onCompleted: {
            console.log("...init message is:>" + message)
        }
    }

    Column {
        spacing: 10

        Button {
            text: "qml中测试c++对象类型"
            onClicked: {
                myObject.num = 102
                myObject.name = "wang"
                testObject.message = "HelloWorld, I love you..."
            }
        }
        Button {
            text: "qml端调用C++端函数"
            onClicked: {
                myObject.printMessage()
            }
        }
        Button {
            text: "qml端发送信号, 连接C++端槽函数"
            onClicked: {
                sendMsg("...qml signal", 66666666)
            }
        }
        Button {
            text: "C++端发送信号, 连接qml端槽函数"
            onClicked: {
                myObject.test1()
            }
        }
    }

    // qml信号连接C++槽函数:方式一
    //    Connections {
    //        target: window
    //        onSendMsg: {
    //            myObject.onMsg("...qml signal", 8888888)
    //        }
    //    }

    //qml信号连接C++槽函数:方式二
    Component.onCompleted: {
        window.sendMsg.connect(myObject.onMsg)
    }

    Connections {
        target: myObject
        onSendCpp1: {
            console.log("......======" + message)
        }
    }
}

参考文章
https://blog.csdn.net/wzz953200463/article/details/129504685

相关推荐
Prejudices1 分钟前
C++如何调用Python脚本
开发语言·c++·python
单音GG4 分钟前
推荐一个基于协程的C++(lua)游戏服务器
服务器·c++·游戏·lua
qing_04060321 分钟前
C++——多态
开发语言·c++·多态
孙同学_21 分钟前
【C++】—掌握STL vector 类:“Vector简介:动态数组的高效应用”
开发语言·c++
charlie1145141911 小时前
Qt Event事件系统小探2
c++·qt·拖放·事件系统
iiiiiankor1 小时前
C/C++内存管理 | new的机制 | 重载自己的operator new
java·c语言·c++
小狮子安度因1 小时前
Qt滑动条美化自定义
qt
小辛学西嘎嘎1 小时前
C/C++精品项目之图床共享云存储(3):网络缓冲区类和main
c语言·开发语言·c++
c语言鹌鹑蛋1 小时前
C++初阶 --- 类和对象(1)
开发语言·c++
Jack黄从零学c++2 小时前
opencv(c++)图像的灰度转换
c++·人工智能·opencv