如何捕获通过 Q_PROPERTY 发出的信号?

How are signals emitted through Q_PROPERTY caught?

http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html

class Message : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged)
public:
    void setAuthor(const QString &a) {
        if (a != m_author) {
            m_author = a;
            emit authorChanged();
        }
    }
    QString author() const {
        return m_author;
    }
signals:
    void authorChanged();
private:
    QString m_author;
};

他们写了emit authorChanged();

我想知道这个信号的插槽在哪里?

发出 authorChanged() 信号时,哪些代码会发生变化?

这段代码是QML(JavaScript)和C++之间通信的一个例子。此代码公开了 author 属性,因此您可以从 JavaScript 代码访问它。如果您从 C++ 端更改作者 属性,您必须通知 QML 引擎。 Q_PROPERTY 宏的 NOTIFY 字段表示一个信号,当它发出时,QML 引擎重新读取 属性.

Message {
    id: msg
    author: "Me"        // this property was defined in c++ side with the 
                        // Q_PROPERTY macro.
}

Text {
    width: 100; height: 100
    text: msg.author    // invokes Message::author() to get this value

    Component.onCompleted: {
        msg.author = "Jonah"  // invokes Message::setAuthor()
    }
}

如果您在 C++ 中使用此 属性,您必须自己提供并连接插槽,但如果您阅读其余内容,则在 Qml 中:

In the above example, the associated NOTIFY signal for the author property is authorChanged, as specified in the Q_PROPERTY() macro call. This means that whenever the signal is emitted — as it is when the author changes in Message::setAuthor() — this notifies the QML engine that any bindings involving the author property must be updated, and in turn, the engine will update the text property by calling Message::author() again.

它表示宏的 NOTIFY 部分通知 QML 引擎它必须连接到此信号并更新涉及此 属性 的所有绑定。

Q_PROPERTY 只是公开了 属性 但实际工作发生在 setAuthor 中,它也发出信号。如果设置了 属性,QML 也会使用此方法。

更新:

问:我想知道这个信号的插槽在哪里?

QML 中的 slots 在 QML 引擎中。

问:发出 authorChanged() 信号时,哪些代码会发生变化?

QML 更新涉及指定 属性 的所有绑定。