C++ 对象处理 QML对象信号
#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
#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;
}
#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();
}
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)
}
}
}
}