0

我正在使用 Qt 5.9.3。我在我的应用程序中声明了以下属性main.qml

代码:

//main.qml
MyQuickItem {

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

// MyQuickItem.h
class MyQuickItem : public QQuickItem {

}

问题:

如何onNextColorChanged在 C++ 端定义?

我知道我也可以nextColor在 C++ 类中作为属性MyQuickItem。像这样

// MyQuickItem.h
class MyQuickItem : public QQuickItem {

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

OnNextColorChanged内部可以监控MyQuickItem吗?

4

1 回答 1

3

我们可以使用 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

完整的示例可以在以下链接中找到。

于 2018-02-15T18:14:36.383 回答