程序运行截图如下:
逻辑:
1.使用Q_PROPERTY宏让元对象能对这个数据成员进行访问
2.在QML系统中注册C++
3.qml进行调用,实现qml与C++的交互
源码如下:
testproperty.h
#ifndef TESTPROPERTY_H
#define TESTPROPERTY_H
#include <QObject>
class TestProperty : public QObject
{
Q_OBJECT
public:
explicit TestProperty(QObject *parent = 0);
Q_PROPERTY(QString title READ title WRITE setTitle NOTIFY titleChanged)
QString title();
void setTitle(QString title);
signals:
void titleChanged();
public slots:
private:
QString m_title;
};
#endif // TESTPROPERTY_H
testproperty.cpp
#include "testproperty.h"
#include <QDebug>
TestProperty::TestProperty(QObject *parent) : QObject(parent)
{
}
QString TestProperty::title()
{
return m_title;
}
void TestProperty::setTitle(QString title)
{
m_title=title;
qDebug()<<"TestProperty::setTitle(QString title) called! "<<title;
emit titleChanged();
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "testproperty.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<TestProperty>("TestProperty",1,0,"TestProperty");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
main.qml
import QtQuick 2.6
import QtQuick.Window 2.2
import TestProperty 1.0
import QtQuick.Controls 1.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Q_PROPERTY 实例")
TextEdit{
id:textEdit
width:240;
font.family: "Helvetica"
font.pointSize: 20
color:"blue"
}
Rectangle{
width: 100
height:200
color:"green"
anchors.centerIn: parent
Button{
anchors.fill: parent
focus: true
onClicked:{
testProperty.title=textEdit.text
}
}
}
TestProperty{
id:testProperty
}
}