1.假設(shè)
1.在c++中創(chuàng)建一個(gè)Person的對(duì)象,
2.在QML中獲取并顯示數(shù)據(jù)
3.在c++中改變數(shù)據(jù)后,顯示的數(shù)據(jù)能進(jìn)行相應(yīng)的改變
也就是說(shuō)我們實(shí)際是在c++中new一個(gè)對(duì)象出來(lái),而把這個(gè)對(duì)象的數(shù)據(jù)在QML里面進(jìn)行顯示
2.具體代碼
// person.h
#ifndef PERSON_H
#define PERSON_H
#include <QObject>
#include <QDeclarativeListProperty>
#include <QList>
#include <QColor>
class Person : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ getName WRITE setName NOTIFY sendNameChange)
Q_PROPERTY(int age READ getAge WRITE setAge NOTIFY sendAgeChange)
public:
explicit Person(QObject *parent = 0);
QString getName(void) const;
void setName(const QString& name);
int getAge(void);
void setAge(int age);
// 一個(gè)簡(jiǎn)單的函數(shù), 獲取藍(lán)色
Q_INVOKABLE QColor getColor(void) const;
Q_INVOKABLE void changeNameAndAge(void);
signals:
void sendNameChange(void);
void sendAgeChange(void);
private:
QString m_Name;
int m_Age;
};
#endif // PERSON_H |
// person.cpp
#include "person.h"
//---------------------------------
//
Person::Person(QObject *parent) :
QObject(parent), m_Name("unknow"), m_Age(0)
{
}
//---------------------------------
//
QString Person::getName(void) const
{
return m_Name;
}
//---------------------------------
//
void Person::setName(const QString& name)
{
m_Name = name;
emit sendNameChange();
}
//---------------------------------
//
int Person::getAge(void)
{
return m_Age;
}
//---------------------------------
//
void Person::setAge(int age)
{
m_Age = age;
emit sendAgeChange();
}
//---------------------------------
//
QColor Person::getColor(void) const
{
return QColor(Qt::blue);
}
//---------------------------------
//
void Person::changeNameAndAge(void)
{
setName("Luly");
setAge(31);
} |
// main.cpp
#include <QtGui/QApplication>
#include <QtDeclarative/QDeclarativeView>
#include <QtDeclarative/QDeclarativeEngine>
#include <QtDeclarative/QDeclarativeComponent>
#include <QtDeclarative/QDeclarativeContext>
#include "person.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Person tmpPerson;
tmpPerson.setName("Tom");
tmpPerson.setAge(25);
QDeclarativeView qmlView;
qmlView.rootContext()->setContextProperty("ps",&tmpPerson);
qmlView.setSource(QUrl::fromLocalFile("../UICtest/UICtest.qml"));
qmlView.show();
return a.exec();
} |
// UICtest.qml
import Qt 4.7
Rectangle {
width: 640
height: 480
Text { text: "Person name:" + ps.name; }
Text { y: 20; text: "Person age:" + ps.age; }
Rectangle{ x: 20; y: 40; width: 20; height: 20; color: ps.getColor();}
MouseArea{
anchors.fill: parent;
// 當(dāng)鼠標(biāo)按下后改變名字和年齡
onClicked: { ps.changeNameAndAge(); }
}
} |
說(shuō)明:
我們?cè)?font style="line-height: 22px; ">c++中創(chuàng)建來(lái)一個(gè)對(duì)象,并且在把這個(gè)對(duì)象導(dǎo)出給QML調(diào)用用,我們?cè)O(shè)置來(lái)屬性,QML中可以直接使用屬性來(lái)進(jìn)行賦值.