QML与c++交互学习笔记(三)

来源:互联网 发布:阿里云的优势和劣势 编辑:程序博客网 时间:2024/05/16 18:07

.导出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.qmlimport Qt 4.7import 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 ,他们分别在发送改变后调用自己对应的信号

具体看源代码这里是设置来矩形框的颜色,文本框中文本。

原创粉丝点击