Posted on 2011-08-04 21:26
RTY 閱讀(631)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
轉(zhuǎn)載隨筆 、
QML
1.導(dǎo)出Person類中的屬性
2.具體導(dǎo)出過(guò)程
1.導(dǎo)出Person一個(gè)顏色屬性,一個(gè)int屬性
注意
1. 當(dāng)需要實(shí)現(xiàn)屬性變化其他引用到此屬性的屬性也跟著變化的情況的話,需要設(shè)置屬性相應(yīng)的信號(hào)
2. 設(shè)置屬性的時(shí)候,使用的類型必須是已經(jīng)導(dǎo)出到QML中的類型
3.具體代碼
// person.h
#ifndef PERSON_H
#define PERSON_H
#include <QObject>
#include <QColor>
class Person : public QObject
{
Q_OBJECT
// 設(shè)置設(shè)置屬性的名字是 bgcolor
// 對(duì)應(yīng)讀取函數(shù)名字 bgColor
// 對(duì)應(yīng)寫函數(shù)名字 setBgColor
// 屬性發(fā)生改變后發(fā)送信號(hào) sendBgColorChange
Q_PROPERTY(QColor bgcolor READ getBgColor WRITE setBgColor NOTIFY sendBgColorChange)
// 設(shè)置設(shè)置屬性的名字是 count
// 對(duì)應(yīng)讀取函數(shù)名字 getCount
// 對(duì)應(yīng)寫函數(shù)名字 setCount
// 屬性發(fā)生改變后發(fā)送信號(hào) sendCountChange
Q_PROPERTY(int count READ getCount WRITE setCount NOTIFY sendCountChange)
public:
explicit Person(QObject *parent = 0);
QColor getBgColor(void) const;
void setBgColor(const QColor& color);
int getCount(void);
void setCount(int count);
signals:
void sendBgColorChange(void);
void sendCountChange(void);
private:
QColor m_Color;
int m_Count;
};
#endif // PERSON_H |
// person.cpp
#include "person.h"
//---------------------------------
//
Person::Person(QObject *parent) :
QObject(parent), m_Color("blue"), m_Count(0)
{
}
//---------------------------------
//
QColor Person::getBgColor(void) const
{
return m_Color;
}
//---------------------------------
//
void Person::setBgColor(const QColor& color)
{
m_Color = color;
emit sendBgColorChange();
}
//---------------------------------
//
int Person::getCount(void)
{
return m_Count;
}
//---------------------------------
//
void Person::setCount(int count)
{
m_Count = count;
emit sendCountChange();
} |
// 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.qml
import Qt 4.7
import People 1.0 //如果是qmlRegisterType<Person>(); 導(dǎo)出就可以注釋這條
Rectangle {
width: 640
height: 480
color: per.bgcolor;
Person{ id: per;}
Text {
id: textlabel;
text: "text " + per.count;
}
MouseArea{
anchors.fill: parent;
onClicked:{
// 當(dāng)鼠標(biāo)按下后,由于屬性上有信號(hào),當(dāng)屬性發(fā)生改變后,
// 所有引用此屬性的值的都相應(yīng)的發(fā)生改變
per.bgcolor = "red";
per.count = 20;
}
}
} |
說(shuō)明:
在person類中,設(shè)置了兩個(gè)屬性bgcolor, count ,他們分別在發(fā)送改變后調(diào)用自己對(duì)應(yīng)的信號(hào)
具體看源代碼,這里是設(shè)置來(lái)矩形框的顏色,文本框中文本。