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")
}