目的:为什么需要使用Q_PROPERTY呢?因为我们在C++中进行逻辑处理的时候,会改变默写状态值,这些状态的改变,我们的UI界面也要同步更改,因此我采用Q_PROPERTY来进行属性绑定使C++和QML的状态同步。
关于Q_PROPERTY的介绍,网上有很多,我不进行介绍,我主要介绍的是在使用中需要注意的地方。在本文中我主要介绍三个我主要使用的内容。READ , WRITE, NOTIFY. 具体的使用注意事项都在实际的使用代码中说明。
C++ 代码:
#include "testproperty.h"
std::mutex TestProperty::s_mutexObj;
TestProperty* TestProperty::s_instance = NULL;
TestProperty::TestProperty()
{
}
TestProperty::~TestProperty()
{
}
void TestProperty::getQmlInfo()
{
static int num = 0;
if(num<=3)
num++;
else
num = 0;
//注意:此处不能直接使用 colorValue = num;但是在QML中我们可以直接使用
setColorValue(num);
}
int TestProperty::getColorValue()
{
return colorValue;
}
void TestProperty::setColorValue(int value)
{
colorValue = value;
emit colorValueChanged(colorValue);
}
TestProperty* TestProperty::GetInstance()
{
s_mutexObj.lock();
if(s_instance==NULL)
s_instance = new TestProperty();
s_mutexObj.unlock();
return s_instance;
}
QML代码:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
function getShowColor(value)
{
switch(value)
{
case 1:
return "red";
case 2:
return "green";
case 3:
return "blue"
case 4:
return "white"
default:
return "black"
}
}
Button{
id:button1
anchors.left: parent.left
anchors.leftMargin: 50
anchors.top: parent.top
anchors.topMargin: 50
width: 80
height: 60
text: qsTr("变色");
onClicked: testProperty.getQmlInfo();
}
Rectangle{
id:testColor
anchors.left: parent.left
anchors.top: button1.bottom
anchors.topMargin: 10
width: parent.width
height: parent.height-90
color: getShowColor(testProperty.colorValue)
}
}
main.cpp 代码
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "testproperty.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
TestProperty* testProperty = TestProperty::GetInstance();
engine.rootContext()->setContextProperty("testProperty",testProperty);
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}