Qml中调用C++类的三种方式详解(三)
程序员文章站
2022-07-16 13:30:35
...
C++创建/获取Qml对象
第一步:新建一个 QmlWindows.qml文件:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
Window{
width: 200
height: 200
color: "red"
}
定义了一个200*200 的红色矩形框,还没有开始使用。
第二步:在main.cpp文件中使用 c++的形式创建
首先在头文件中加入:
#include <QQmlComponent>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "qmlcpp.h"
#include <QJSValue>
#include <QQmlEngine>
#include <QQmlComponent>
int main(int argc, char *argv[])
{
qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
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);
QQmlComponent qmlComponent(&engine);
qmlComponent.loadUrl(QUrl(QStringLiteral("qrc:/QmlWindow.qml")));
QObject* qmlWindows = qmlComponent.create();
qmlWindows->setParent(engine.rootObjects()[0]);
engine.rootContext()->setContextProperty("qmlWindows",qmlWindows);
return app.exec();
}
主要代码是:
QQmlComponent qmlComponent(&engine);
qmlComponent.loadUrl(QUrl(QStringLiteral("qrc:/QmlWindow.qml")));
QObject* qmlWindows = qmlComponent.create();
qmlWindows->setParent(engine.rootObjects()[0]);
engine.rootContext()->setContextProperty("qmlWindows",qmlWindows);
其中 engine.rootObjects()[0] 指的是主窗体。
第三步,在其他的qml文件中就可以直接进行调用
import QtQuick 2.12
import QtQuick.Controls 2.12
Item {
Button{
id:btn
height: 48
width: 120
text: "1"
anchors.centerIn: parent
onClicked: {
qmlWindows.color="green";
qmlWindows.width=200;
qmlWindows.visible = true;
}
}
Button{
id:btn1
height: 48
width: 120
anchors.top: btn.bottom
anchors.topMargin: 12
anchors.horizontalCenter: btn.horizontalCenter
onClicked: {
qmlWindows.width=400;
qmlWindows.color="yellow"
}
}
}
点击第一个按钮,使得 qmlWindows.qml这个 红色矩形 变为绿色,并可见
点击第一个按钮,使得 qmlWindows.qml这个 矩形 变为黄色,并使得宽度为400。