1、简介
通过C++创建qml需要使用两个类QQmlEngine和QQmlComponent
2、代码
cpp
#include <QQmlComponent>
#include <QQmlEngine>
#include <QQuickWindow>
#include <QDebug>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlEngine qmlEngine;
QQmlComponent* component = new QQmlComponent(&qmlEngine, "qrc:/main.qml");
// qml编写有问题会创建失败,可以使用errorString打印失败信息
QObject* pMainObj = component->create();
qDebug() << component->errorString();
// 在此将QObject转为QQuickWindow是因为qml文件顶层是Window,如果是Item,则是QQuickItem *
QQuickWindow* pQuickWindow = dynamic_cast<QQuickWindow *>(pMainObj);
pQuickWindow->show();
return app.exec();
}
qml
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
}
该文介绍了如何使用C++与QML集成,通过QQmlEngine和QQmlComponent类来加载并创建QML对象。示例代码展示了一个简单的QML窗口显示程序,当QML文件有错误时,还会打印错误信息。
324

被折叠的 条评论
为什么被折叠?



