简体   繁体   English

Qt:如何在C ++端而不是QML上监视Q_PROPERTY更改

[英]Qt : How to monitor a Q_PROPERTY change on C++ side instead of QML

I am using Qt 5.9.3. 我正在使用Qt 5.9.3。 I have following property declared in my app's main.qml 我在应用的main.qml声明了以下属性

Code: 码:

//main.qml
MyQuickItem {

    property color nextColor
    onNextColorChanged: {
        console.log("The next color will be: " + nextColor.toString())
    }
}

// MyQuickItem.h
class MyQuickItem : public QQuickItem {

}

Question: 题:

How can I make onNextColorChanged be defined in the C++ side? 如何在C ++端定义onNextColorChanged

I know that I can also make nextColor as a property inside C++ class MyQuickItem . 我知道我也可以将nextColor用作C ++类MyQuickItem的属性。 like so 像这样

// MyQuickItem.h
class MyQuickItem : public QQuickItem {

    Q_PROPERTY(QColor nextColor READ nextColor WRITE setNextColor NOTIFY nextColorChanged)
}

Is it possible to monitor OnNextColorChanged inside MyQuickItem ? 是否有可能监测OnNextColorChanged里面MyQuickItem

We can use the QMetaObject to obtain the property and the signal, then we connect it through the old style: 我们可以使用QMetaObject获取属性和信号,然后通过旧样式将其连接:

#ifndef MYQUICKITEM_H
#define MYQUICKITEM_H

#include <QQuickItem>
#include <QDebug>

class MyQuickItem : public QQuickItem
{
    Q_OBJECT
public:
    MyQuickItem(QQuickItem *parent = Q_NULLPTR): QQuickItem(parent){}
protected:
    void componentComplete(){
        int index =metaObject()->indexOfProperty("nextColor");
        const QMetaProperty property = metaObject()->property(index);
        if (property.hasNotifySignal()){
            const QMetaMethod s = property.notifySignal();
            QString sig = QString("2%1").arg(QString(s.methodSignature()));
            connect(this, sig.toStdString().c_str() , this, SLOT(onNextColorChanged()));
        }
    }
private slots:
    void onNextColorChanged(){
        int index =metaObject()->indexOfProperty("nextColor");
        const QMetaProperty property = metaObject()->property(index);
        qDebug()<<"color" << property.read(this);
    }
};

#endif // MYQUICKITEM_H

The complete example can be found in the following link . 完整的示例可以在以下链接中找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM