您的位置:首页 > 编程语言 > C语言/C++

QT C++ QML交互之注册C++对象给QML

2012-12-20 10:03 351 查看
在QT中C++可以与QML进行交互,这里介绍如何通过将C++对象注册给QML来使用。

首先建立一个QML工程(具体过程参看前面的文章QML学习),然后创建一个从QObject派生的对象,假设为:QmlInterAction,相应的头文件和源文件如下:

qmlinteraction.h

#ifndef QMLINTERACTION_H
#define QMLINTERACTION_H

#include <QObject>

class QmlInterAction : public QObject
{
Q_OBJECT

Q_PROPERTY(QString inerString READ getString WRITE setString NOTIFY stringChanged)

public:
explicit QmlInterAction(QObject *parent = 0);

signals:
void stringChanged();

public slots:
QString getString();
void setString(QString string);

private:
QString         m_string;

};

#endif // QMLINTERACTION_H

qmlinteraction.cpp

#include "qmlinteraction.h"

#include <QtGui/QMessageBox>

QmlInterAction::QmlInterAction(QObject *parent) :
QObject(parent)
{
m_string = "hello";
}

QString QmlInterAction::getString()
{
return m_string;
}

void QmlInterAction::setString(QString string)
{
m_string = string;
emit stringChanged();

QString strContent = "Button " + string + " is clicked!";
QMessageBox::information(NULL, "Hello", strContent, QMessageBox::Yes);
}

这样之后QmlInterAction类就可以注册到QML中去了,下面就是注册的过程,在main.cpp中:

#include <qdeclarative.h>
#include <QDeclarativeView>
#include <QApplication>
#include "qmlapplicationviewer.h"
#include "qmlinteraction.h"

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QmlApplicationViewer viewer;
//注册
qmlRegisterType<QmlInterAction>("QmlInter", 1,0,"QmlInterAction");
viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
viewer.setMainQmlFile(QLatin1String("qml/GroupChat/main.qml"));
viewer.showExpanded();
return app.exec();
}

好了关于C++部分的工作已经完成了,接下来就可以在QML文件中进行使用了

main.qml

import QtQuick 1.1
import QmlInter 1.0

Rectangle {
width: 360
height: 360

//some other elements can use the qmlInterAction's properties

//do something others ...

QmlInterAction//Instance of QmlInterAction
{
id : qmlInterAction
}
}

完。

本文出自 “lilingshui” 博客,请务必保留此出处http://qsjming.blog.51cto.com/1159640/1094660
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: