QML与C++交互(基础)
利用全局对象 上下文对象访问C++的数据(rootContext(),setContextProperty())
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
//全局对象,能够被QML端访问到这个属性
QQmlContext* context = engine.rootContext();
//SCREEN_WIDTH这个属性就能够被SCREEN_WIDTH获取到了
context->setContextProperty("SCREEN_WIDTH",2000);
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();
}
C++端获取不同电脑显示器屏幕的宽,设置为全局对象能够被QML访问到。
//main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QScreen>
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 //此时就可以调用C++端的这个属性,设置宽度
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)
}
}