QML与c++交互学习笔记(二)

来源:互联网 发布:阿里云的优势和劣势 编辑:程序博客网 时间:2024/06/05 16:05


1.导出Person类中的成员方法

2.具体导出过程

导出的方法

1.使用Q_INVOKABLE

2.使用 槽机制


3.具体代码



// person.h#ifndef PERSON_H#define PERSON_H#include <QObject>class Person : public QObject{    Q_OBJECTpublic:    explicit Person(QObject *parent = 0);    Q_INVOKABLE void FirstEcho(void);public slots:    void SecondEcho(void);};#endif // PERSON_H


// person.cpp#include "person.h"Person::Person(QObject *parent) :    QObject(parent){}void Person::FirstEcho(void){    // 简简单单打印一句话    qDebug("call Person::FirstEcho");}void Person::SecondEcho(void){    qDebug("call Person::SecondEcho");}


// main.cpp#include <QtGui/QApplication>#include <QtDeclarative/QDeclarativeView>#include <QtDeclarative/QDeclarativeEngine>#include <QtDeclarative/QDeclarativeComponent>#include "person.h"int main(int argc, char *argv[]){    QApplication a(argc, argv);    qmlRegisterType<Person>("People",1,0,"Person");    //qmlRegisterType<Person>();    QDeclarativeView qmlView;    qmlView.setSource(QUrl::fromLocalFile("../UICtest/UICtest.qml"));    qmlView.show();    return a.exec();}


// UICtest.qmlimport Qt 4.7import People 1.0 //如果是qmlRegisterType<Person>(); 导出就可以注释这条Rectangle {    width: 640    height: 480    Person{ id: per;}    MouseArea{        anchors.fill: parent;        onClicked:{            per.FirstEcho();            per.SecondEcho();        }    }}


说明:

这里导出了两个函数分别是FirstEcho SecondEcho 两个函数,这两个函数本别是使用

FirstEcho使用使用 Q_INVOKABLE导出,SecondEcho直接使用槽

调用函数在控制台输出一些信息,这里是在鼠标点击界面后出发的