如何注册Qt C++对象以在QML中使用它

How to register Qt C++ object to use it in QML

本文关键字:QML 对象 C++ 何注册 注册 Qt      更新时间:2023-10-16

我尝试注册 ColorsSource *pSource 对象以在 QML 中使用它,但我在字符串中得到错误: "QQmlContext *context = myObject->rootContext((;" 对__imp__ZNK12QQuickWidget11rootContextEv的未定义引用

主.cpp

#include "ColorsSource.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQuickWidgets/QQuickWidget>
#include <QQmlContext>
int main(int argc, char *argv[])
{
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);
ColorsSource *pSource = new ColorsSource;
QQuickWidget *myObject = static_cast<QQuickWidget*>(engine.rootObjects().first());
QQmlContext *context = myObject->rootContext();
context->setContextProperty("ColorSource", pSource);
return app.exec();
}

您缺少quickwidgetsQt模块。这就是为什么它找不到这些符号的原因。如果您使用 qmake,请将QT += quickwidgets添加到您的专业文件中。

但那不会是你的问题。QQuickWidgets是用于显示一些QQuick代码的小部件,用于Widgets应用程序。但是当你使用QQmlApplicationEngine时,你是在快速中工作。你的rootObject()不会是QQuickWidget。因此,与其寻找 QQuickWidget,不如访问引擎 rootContext - 替换:

QQuickWidget *myObject = static_cast<QQuickWidget*>(engine.rootObjects().first());
QQmlContext *context = myObject->rootContext();
context->setContextProperty("ColorSource", pSource);

QQmlContext *context = engine.rootContext();
context->setContextProperty("ColorSource", pSource);

这将使您的代码更不容易出错。

此外,在不相关的笔记中,您应该始终检查您的指针,以确保您的static_cast一切正常。否则,如果引擎 rootObjects 为空或第一个不是 QQuickWidget,您将崩溃。