Posted on 2011-08-04 21:26
RTY 閱讀(631)
評論(0) 編輯 收藏 引用 所屬分類:
轉載隨筆 、
QML
1.導出Person類中的屬性
2.具體導出過程
1.導出Person一個顏色屬性,一個int屬性
注意
1. 當需要實現屬性變化其他引用到此屬性的屬性也跟著變化的情況的話,需要設置屬性相應的信號
2. 設置屬性的時候,使用的類型必須是已經導出到QML中的類型
3.具體代碼
// person.h
#ifndef PERSON_H
#define PERSON_H
#include <QObject>
#include <QColor>
class Person : public QObject
{
Q_OBJECT
// 設置設置屬性的名字是 bgcolor
// 對應讀取函數名字 bgColor
// 對應寫函數名字 setBgColor
// 屬性發生改變后發送信號 sendBgColorChange
Q_PROPERTY(QColor bgcolor READ getBgColor WRITE setBgColor NOTIFY sendBgColorChange)
// 設置設置屬性的名字是 count
// 對應讀取函數名字 getCount
// 對應寫函數名字 setCount
// 屬性發生改變后發送信號 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>(); 導出就可以注釋這條
Rectangle {
width: 640
height: 480
color: per.bgcolor;
Person{ id: per;}
Text {
id: textlabel;
text: "text " + per.count;
}
MouseArea{
anchors.fill: parent;
onClicked:{
// 當鼠標按下后,由于屬性上有信號,當屬性發生改變后,
// 所有引用此屬性的值的都相應的發生改變
per.bgcolor = "red";
per.count = 20;
}
}
} |
說明:
在person類中,設置了兩個屬性bgcolor, count ,他們分別在發送改變后調用自己對應的信號
具體看源代碼,這里是設置來矩形框的顏色,文本框中文本。