示例代码
详细请见http://www.digitalfanatics.org/projects/qt_tutorial/chapter02.html
#ifndef PROPOBJECT_H
#define PROPOBJECT_H

#include
#include

class PropObject : public QObject
{
Q_OBJECT

Q_PROPERTY( TestProperty testProperty READ testProperty WRITE setTestProperty )
Q_ENUMS( TestProperty )

Q_PROPERTY( QString anotherProperty READ anotherProperty )

public:
PropObject( QObject *parent=0, char *name=0 );

enum TestProperty { InitialValue, AnotherValue };

void setTestProperty( TestProperty p );
TestProperty testProperty() const;

QString anotherProperty() const { return QString( “I’m read-only!” ); }

private:
TestProperty m_testProperty;
};

#endif

请注意Q_PROPERTY的参数之间没有逗号,语法为属性的类型,后面接名字,然后是READ或者WRITE,最后接相应的函数名字
读和写属性的函数的要求(偷懒不翻译了:):
There is nothing special about the read and write member functions. The only restriction is that the reader must be of the parameters type and take no arguments (i.e. it has to be of the type void) while the writer must accept only one argument and it has to be of the parameter type.
It is common practice to declare write functions as slots. This increases the easy of re-use since most write functions are natural slots. Some of these are also candidates for emitting signals.
例如:propobject.cpp.
#include “propobject.h”

PropObject::PropObject( QObject *parent, char *name ) : QObject( parent, name )
{
m_testProperty = InitialValue;
}

void PropObject::setTestProperty( TestProperty p ) { m_testProperty = p; }
PropObject::TestProperty PropObject::testProperty() const { return m_testProperty; }

#include
#include

#include “propobject.h”

int main( int argc, char **argv )
{
QApplication a( argc, argv );

QObject *o = new PropObject();

std::cout << o->property( “testProperty” ).toString() << std::endl;

o->setProperty( “testProperty”, “AnotherValue” );
std::cout << o->property( “testProperty” ).toString() << std::endl;

std::cout << o->property( “anotherProperty” ).toString() << std::endl;

return 0;
}

输出:
$ ./prop
0
1
I’m read-only!
$


评论

该日志第一篇评论

发表评论

评论也有版权!