QML与C++通信例子

myclass.h

#ifndef MYCLASS_H
#define MYCLASS_H

#include <QObject>
#include<QString>
class MyClass : public QObject
{
    Q_OBJECT
    //暴露给QML 属性
    Q_PROPERTY(QString mystring READ getString WRITE setString NOTIFY mystringChanged)
private:
    QString * m_pstring;
public:
    explicit MyClass(QObject *parent = 0);
     Q_INVOKABLE QString getString(); //Q_INVOCABLE暴露给 QML
    Q_INVOKABLE void setString(QString string);
    ~MyClass();

signals:
   void  mystringChanged(QString value); //信号
public slots:

};

#endif // MYCLASS_H
myclass.cpp

#include "myclass.h"

MyClass::MyClass(QObject *parent) : QObject(parent)
{
    this->m_pstring=new QString("默认值");
}

MyClass::~MyClass()
{
    delete this->m_pstring;
}
QString MyClass::getString()
{
    setString("xx");
    return *(this->m_pstring);
}
void MyClass::setString(QString string){
    *(this->m_pstring)=string;
    emit mystringChanged(string);//发送信号
}

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include<QtQml>
#include<myclass.h>
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    //注册到QML
    qmlRegisterType<MyClass>("RegisterMyType",1,0,"MyClassType");
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

main.qml

import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.2
import RegisterMyType 1.0 //导入
Window {
    visible: true
    Button{
        id:btn1;
        height:20;
        width:60;
        text:"按钮";
        onClicked: {
            //qml操作c++
            btn1.text=myobj.mystring;
        }
    }
    Label{
        id:label1;
        text:"初始值";
        anchors.left:btn1.right;
        anchors.leftMargin: 12;
    }
    //创建对象
    MyClassType
    {
         id:myobj;
    }
    //连接信号 到qml
    Connections{
        target:myobj;
        onMystringChanged:label1.text="改变了值是:"+value; //这里的value是signal信号函数里面的参数
    }

}



©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页