如何注册Qt C++对象以在QML中使用它
How to register Qt C++ object to use it in QML
我尝试注册 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();
}
您缺少quickwidgets
Qt模块。这就是为什么它找不到这些符号的原因。如果您使用 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,您将崩溃。
相关文章:
- QML 对象的销毁顺序
- 使用 createComponent 动态创建 QML 对象
- 可以在 QObject::connect() C++中连接 QML 对象现有信号?
- 如何删除 QML 对象
- 销毁 qml 对象后的信号槽连接
- 将 QObject 指针从 QML 对象传递到C++
- 使用C 访问QT / QML对象
- 如何使用 API 获取 QML 对象的 id 属性C++
- 如何在C++运行时更改QML对象的属性
- 与C++代码中的 qml 对象交互
- 如何从C++访问嵌套的 QML 对象
- 使用cpp代码从加载的qml访问qml对象
- 从C++访问 QML 对象
- 如何从C++调用 QML 对象的方法
- 从具有指定属性的C++创建 QML 对象
- 在现有 C++ QT 项目中实例化 QML 对象
- QML 对象属性的部分序列化
- 区分C++中QML对象的类类型
- 使用c++设置qml对象的属性
- 将qml对象添加到QGraphicsScene