QML与C++通信例子

myclass.h

#ifndef MYCLASS_H
#define MYCLASS_H

#include 
#include
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 
#include 
#include
#include
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    //注册到QML
    qmlRegisterType("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信号函数里面的参数
    }

}

QML与C++通信例子_第1张图片 QML与C++通信例子_第2张图片

你可能感兴趣的:(C++Qt框架,C++,Qt框架)