- 利用全局对象 上下文对象访问C++的数据(rootContext(),setContextProperty())
- QML组件怎么私有化组件的属性不让外部调用?(QtObject)
//main.cpp
#include
#include
#include
#include
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
//全局对象 上下文对象
QQmlContext* context = engine.rootContext();
QScreen *screen = QGuiApplication::primaryScreen();
QRect rect = screen->virtualGeometry();
//QML端可以通过SCREEN_WIDTH获取C++端的数据rect.width()的值
context->setContextProperty("SCREEN_WIDTH",rect.width());
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();
}
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: SCREEN_WIDTH
height: 480
title: qsTr("Hello World")
}
利用engine.rootContext()创建上下文对象,setContextProperty设置Qml获取到的C++端的值
QML组件怎么私有化组件的属性不让外部调用?(QtObject)mian.qml
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: SCREEN_WIDTH
height: 480
title: qsTr("Hello World")
// QtObject{
// }
MyRectangle{
Component.onCompleted: {
//别名访问这个变量
attr.testValue = 200
console.log(attr.testValue)
}
}
}
MyRectangle.qml
import QtQuick 2.0
import QtQuick.Controls 2.5
Rectangle{
//property int testValue: 0
width: 200
height: 100
color: "black"
property alias attr: attributes //设置别名访问这个变量
QtObject {
id: attributes
//私有化这个属性
property int testValue: 0
}
Component.onCompleted: {
//通过id访问这个变量
console.log(attributes.testValue)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)