Qt小例子学习50 - c++ 监控 Q_PROPERTY的值
MyQuickItem.cpp
#ifndef MYQUICKITEM_H
#define MYQUICKITEM_H
#include <QDebug>
#include <QQuickItem>
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
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import com.eyllanes.items 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
MyQuickItem {
id: mitem
property color nextColor
onNextColorChanged: {
console.log("The next color will be: " + nextColor.toString())
}
}
Timer {
interval: 500; running: true; repeat: true
onTriggered: mitem.nextColor = Qt.rgba( Math.random() % 256, Math.random() % 256, Math.random() % 256)
}
}
main.cpp
#include "myquickitem.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
qmlRegisterType<MyQuickItem>("com.eyllanes.items", 1, 0, "MyQuickItem");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}