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

QML 访问C++中的 对象,以及函数

2015-12-09 19:42 447 查看
/main.qml

//====================================================

// myclass.h

//====================================================

#include
#include

#include

#include

#include

class LTest : public QObject

{

Q_OBJECT

public:

LTest() {}

LTest(QDeclarativeContext *context)

: m_pContext(context)

{}

public slots:

void changedColor() {

m_pContext->setContextProperty("backgroundColor", QColor(Qt::red));

}

signals:

void data(QVariant data);

private:

QDeclarativeContext *m_pContext;

};

//====================================================
// main.cpp
//====================================================
#include
#include
#include
#include
#include
#include"myclass.h"

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

QDeclarativeView view;
QDeclarativeContext *context = view.rootContext();
context->setContextProperty("backgroundColor",
QColor(Qt::yellow));

LTest test(context);//
context->setContextProperty("test", &test);

view.setSource(QUrl::fromLocalFile("main.qml"));
view.show();

return app.exec();
}

======================================================
这个程序,官方网站有,我只是对做了一点点扩展,
1. 导出对象
// 在c++中创建一个对象
LTest test(context);

// 导出一个对象test到qml中
context->setContextProperty("test", /*qml 中能直接使用这个名访问C++中的对象*/
&test /*c++的对象名*/);

2. 导出变量, backgroundColor
context->setContextProperty("backgroundColor",
QColor(Qt::yellow));


2. 在qml中可以看到rectangle的背景颜色使用的是
backgroundColor

color: backgroundColor
只要在c++中改变 backgroundColor 的值,qml中的背景颜色也会自动变化。

3. qml中调用c++中的函数(对象的函数,必须是声明为 slot 的函数)。
public slots:
void changedColor() {//c++中定义的插槽函数
m_pContext->setContextProperty("backgroundColor", QColor(Qt::red));
}

qml中访问该函数,

onClicked: {
// call the c++'s function,from qml
test.changedColor();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: