main.qml
import QtQuick 2.14
import QtQuick.Controls 2.14
import MyObj 1.0
ApplicationWindow {
id: window
visible: true
width: screen_WIDTH
height: 480
objectName: "window"
title: qsTr("Scroll")
signal qmlSig(int i,string s)
function qmlSlot(i,s){
console.log("qml",i,s)
}
Button{
objectName: "mybutton"
onClicked: {
MyObject.func()
}
}
}
myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <QObject>
#include <QtQml>
class MyObject : public QObject
{
Q_OBJECT
public:
explicit MyObject(QObject *parent = nullptr);
static MyObject* getinstance();
int iValue() const;
void setIValue(int iValue);
QString sString() const;
void setSString(const QString &sString);
Q_INVOKABLE void func();
public slots:
void cppSlot(int i,QString s);
signals:
void cppSig(QVariant i, QVariant s);
private:
int m_iValue;
QString m_sString;
Q_PROPERTY(int iValue READ iValue WRITE setIValue )
Q_PROPERTY(QString sString READ sString WRITE setSString )
};
#endif
myobject.cpp
#include "myobject.h"
MyObject::MyObject(QObject *parent) : QObject(parent)
{
}
MyObject *MyObject::getinstance()
{
static MyObject* obj= new MyObject();
return obj;
}
int MyObject::iValue() const
{
return m_iValue;
}
void MyObject::setIValue(int iValue)
{
m_iValue = iValue;
}
QString MyObject::sString() const
{
return m_sString;
}
void MyObject::setSString(const QString &sString)
{
m_sString = sString;
}
void MyObject::func()
{
emit cppSig(101,"wangwang");
qDebug() << __FUNCTION__;
}
void MyObject::cppSlot(int i, QString s)
{
qDebug() << __FUNCTION__ << " " << i << " " << s;
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QScreen>
#include <QRect>
#include <QQmlContext>
#include "myobject.h"
#include <QObject>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QQmlContext* context = engine.rootContext();
QScreen* screen = QGuiApplication::primaryScreen();
QRect rect = screen->virtualGeometry();
context->setContextProperty("screen_WIDTH",200);
qmlRegisterType<MyObject>("MyObj",1,0,"MyObject");
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);
auto list = engine.rootObjects();
auto objName = list.first()->objectName();
qDebug() << objName << endl;
auto objName2 = list.first()->findChild<QObject*>("mybutton");
qDebug() << objName2;
auto window = list.first();
QObject::connect(MyObject::getinstance(),SIGNAL(cppSig(QVariant,QVariant)),
window, SLOT(qmlSlot(QVariant,QVariant)));
return app.exec();
}