C++ 对象处理 QML对象信号

C++ 对象处理 QML对象信号

  • 目录结构

  • person.h
#ifndef PERSON_H
#define PERSON_H

#include <QObject>
#include <QString>

class Person : public QObject
{
    Q_OBJECT
public:
    using QObject::QObject;
    Person(QString name, qint32 age) noexcept;
    Q_INVOKABLE void printInfo()const noexcept;  //qml中调用
public slots:
    void onQmlBtnClicked(int )const noexcept;

private:
    QString   m_strName;
    qint32    m_iAge;

};

#endif // PERSON_H
  • person.cpp
#include "Person.h"
#include <QDebug>

Person::Person(QString name, qint32 age) noexcept: m_strName(qMove(name)),m_iAge(age)
{
}

void Person::printInfo() const noexcept
{
    qDebug()<< __FILE__ << ":"<< __FUNCTION__ << "name: " << m_strName << "age: " << m_iAge;  //qml中调用
}

void Person::onQmlBtnClicked(int num) const noexcept
{
     qDebug()<< __FILE__ << ":"<< __FUNCTION__ << "Qml Button Siganl Slot" << num;
}
  • main.cpp
#include "./Person.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QMetaObject>   //元对象系统
#include <QQmlContext>
#include <QDebug>

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

    Person person("Miao", 72);
    auto context = engine.rootContext();
    context->setContextProperty("Person", &person);

     engine.load(url);
    //调用qml
    auto root = engine.rootObjects();
    auto qmlBtn = root.first()->findChild<QObject*>("qmlButton");

    //信号连接
    QObject::connect(qmlBtn, SIGNAL(countNum(int)), &person, SLOT(onQmlBtnClicked(int)));

    return app.exec();
}
  • main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("QML与CPP")

    Button{
        objectName: "qmlButton"
        property  int num: 0
        signal countNum(int num)
        text: "clicked"
        onClicked: {
            Person.printInfo();
            ++num
            if(!(num % 3))
            {
                countNum(num)
            }
        }
    }
}
  • 输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值