QML学习笔记1(qml调用c++函数)

//testclass.h
#ifndef TESTCLASS_H
#define TESTCLASS_H

#include <QObject>
#include <QDateTime>
#include <QDebug>

class TestClass : public QObject
{
    Q_OBJECT
public:
    explicit TestClass(QObject *parent = nullptr);

    QString getMessage() const;
    void setMessage(const QString &value);
public slots:
     void doSamething();
     QString getTime();
signals:
    void showMessage(QString oldstr,QString newstr);
private:
    QString message="默认消息";
    int count=0;
    Q_PROPERTY(QString msg READ getMessage WRITE setMessage NOTIFY showMessage)
};

#endif // TESTCLASS_H
//testclass.cpp
#include "testclass.h"

TestClass::TestClass(QObject *parent) : QObject(parent)
{

}

QString TestClass::getMessage() const
{
    return message;
}

void TestClass::setMessage(const QString &value)
{
    if(message != value)
    {
        qDebug()<<"修改";
        showMessage(message,value);
        message=value;
    }
}

void TestClass::doSamething()
{
    setMessage(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
}

QString TestClass::getTime()
{
    return  QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
}
//main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "testclass.h"
int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    qmlRegisterType<TestClass>("Myclass",1,0,"Test");

    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);
    engine.load(url);

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

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")


    Test{
        id:test1
    }
    Connections{
        target: test1
        function onShowMessage(o,n){
            console.log("修改消息:",o,n);
        }
    }

    Button {
        width: 50
        height: 50
        text: "测试"
        onClicked: {
            //test1.msg=test1.getTime();
            test1.doSamething();
        }
    }
}

1,注册类,有点像C# ioc容器,实现原理可能类似?

qmlRegisterType<TestClass>("Myclass",1,0,"Test");
TestClass:类名称
Myclass,1,0:用于导入的名称,主版本和次版本,import Myclass 1.0
Test:用于qml调用的组件或对象

2,Q_PROPERTY 宏属性定义,暴露qml调用的属性

3,public slots和Q_INVOKABLE 需要找到区别

猜你喜欢

转载自blog.csdn.net/dwm88888888/article/details/131156731