原型:
class ClassName : public QObject
{
Q_OBJECT
QString m_test;
Q_PROPERTY(QString test READ test WRITE setTest NOTIFY testChanged)
signals:
void testChanged(QString arg);
public slots:
void setTest(QString arg)
{
if (m_test != arg) {
m_test = arg;
emit testChanged(arg);
}
}
public:
QString test() const
{
return m_test;
}
}
为了代码简洁,可先定义一个Qml属性导出宏:
#define QML_PROPERTY(type, name, \
READ, getter, \
WRITE, setter, \
NOTIFY, notifyer\
) \
type m_##name; \
Q_PROPERTY(type name READ getter WRITE setter NOTIFY notifyer) \
public: type getter##() const { return m_##name; } \
public Q_SLOTS: void setter##(type arg) { if (m_##name != arg) {m_##name = arg; emit notifyer##(arg);}} \
Q_SIGNALS: \
void notifyer##(type arg); \
private:
则以上类可如下定义:
class ClassName : public QObject
{
Q_OBJECT
QML_PROPERTY(QString, test, READ, test, WRITE, setTest, NOTIFY, testChanged)
}
如此无论是通过类注册还是实例上下文,可在Qml中可以访问该属性,并可以调用其方法。