MyObject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <QObject>
#include <QDebug>
class MyObject : public QObject
{
Q_OBJECT
public:
explicit MyObject(QObject *parent = nullptr);
static MyObject* getInstance();
int iValue() const;
void setIValue(int iValue);
//这样 func 可以直接在qml调用
Q_INVOKABLE void func();
QString sString() const;
void setSString(const QString &sString);
private:
int m_iValue;
QString m_sString;
Q_PROPERTY(int iValue READ iValue WRITE setIValue NOTIFY iValueChanged)
signals:
//这里因为qml function的槽函数参数是QVariant类型
void cppSig(QVariant,QVariant);
void iValueChanged();
public slots:
void cppSlot(int i,QString s);
};
#endif // MYOBJECT_H
MyObject.cpp
#include "myobject.h"
MyObject::MyObject(QObject *parent) : QObject(parent)
{
}
MyObject *MyObject::getInstance()
{
static MyObject* myObject=new MyObject;
return myObject;
}
int MyObject::iValue() const
{
return m_iValue;
}
void MyObject::setIValue(int iValue)
{
m_iValue = iValue;
}
void MyObject::func()
{
qDebug()<<__FUNCTION__;
}
void MyObject::cppSlot(int i, QString s)
{
qDebug()<<__FUNCTION__<<" "<<i<<" "<<s;
}
QString MyObject::sString() const
{
return m_sString;
}
void MyObject::setSString(const QString &sString)
{
m_sString = sString;
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QScreen>
#include <myobject.h>
#include <QObject>
#include <QList>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
//注册MyObject 这样必须在qml创建对象
qmlRegisterType<MyObject>("MyObj",1,0,"MyObject");
//注册MyObject 这样无需在qml创建对象 新版本不可用
// qmlRegisterSingletonInstance("MyObj",1,0,"MyObject",MyObject::getInstance());
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);
engine.load(url);
QList<QObject*> list=engine.rootObjects();
auto window=list.first();
//qml连接cpp
QObject::connect(window,SIGNAL(qmlSig(int,QString)),MyObject::getInstance(),SLOT(cppSlot(int,QString)));
//cpp连接qml
QObject::connect(MyObject::getInstance(),SIGNAL(cppSig(QVariant,QVariant)),window,SLOT(qmlSlot(QVariant,QVariant)));
return app.exec();
}
main.qml
import QtQuick 2.0
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
//导入MyObj
import MyObj 1.0
Window {
id:window
width: 400
height: 300
color: "white"
visible: true
property int value:myobj.iValue
signal qmlSig(int i,string s);
function qmlSlot(i,s){
console.log("qml",i,s)
}
MyObject{
id:myobj
iValue: 10
}
Button{
onClicked: {
myobj.iValue=2000//修改变量
console.log(value)//结果是10没有发生动态绑定
//触发cpp的函数
myobj.func()
/*
Qt Creator 4.9.1
Based on Qt 5.12.3 (MSVC 2017, 32 bit)
*/
}
}
}