Qt之自定义属性Q_PROPERTY 以及QObject 源码展示

Q_PROPERTY()是一个宏,用来在一个类中声明一个属性property,由于该宏是qt特有的,需要用moc进行编译,故必须继承于QObject类:

#ifndef TESTPROPERTY_H
#define TESTPROPERTY_H

#include 

class TestProperty : public QObject
{
   
    Q_OBJECT
public:
    explicit TestProperty(QObject *parent = nullptr);
    Q_PROPERTY(QString title READ title WRITE setTitle NOTIFY titleChanged);

    QString title();
    void setTitle(QString strTitle);


signals:
    void titleChanged();

public slots:

private:
    QString     m_title;

};

#endif // TESTPROPERTY_H
_____________________________
#include "TestProperty.h"

TestProperty::TestProperty(QObject *parent) : QObject(parent)
{
   

}

QString TestProperty::title()
{
   
    return  m_title;
}

void TestProperty::setTitle(QString strTitle)
{
   
    m_title = strTitle;
    emit titleChanged();
}
_____________________________

在main函数中注册这个类,导出到qml中,在qml中调用title属性
___________________________
#include 
#include 
#include 
#include "TestProperty.h"

int main(int argc, char *argv[])
{
   
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    qmlRegisterType<TestProperty>("TestProperty", 1, 0, "TestProperty");
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}
/在qml中调用title属性//
import QtQuick 2.9
import QtQuick.Window 2.2
import TestProperty 1.0

Window {
   
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello Qt")

    TestProperty{
   
        id: testProperty
        title: qsTr("Hello World")
    }

    Component.onCompleted: {
   
        title = testProperty.title;
    }
}
class Q_CORE_
EXPORT QObjectData {
   
public:
    virtual ~QObjectData() = 0;
    QObject *q_ptr;
    QObject *parent;
    QObjectList children;

    uint isWidget : 1;
    uint blockSig : 1;
    uint wasDeleted : 1;
    uint isDeletingChildren : 1;
    uint sendChildEvents : 1;
    uint receiveChildEvents : 1;
    u

你可能感兴趣的:(qt)