简体   繁体   English

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

[英]How to register Qt C++ object to use it in QML

I try to register ColorsSource *pSource object to use it in QML but I get erreor in string: "QQmlContext *context = myObject->rootContext();"我尝试注册 ColorsSource *pSource object 以在 QML 中使用它,但在字符串中出现错误:“QQmlContext *context = myObject->rootContext();” undefined reference to __imp__ZNK12QQuickWidget11rootContextEv__imp__ZNK12QQuickWidget11rootContextEv的未定义引用

main.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();
}

You are missing the quickwidgets Qt module.您缺少快速小quickwidgets模块。 Thats why it cannot find these Symbols.这就是它找不到这些符号的原因。 If you use qmake, add QT += quickwidgets to your pro file.如果您使用 qmake,请将QT += quickwidgets添加到您的 pro 文件中。

But that won't be your Problem.但这不是你的问题。 QQuickWidgets are widgets to display some QQuick code, to be used in a Widgets application. QQuickWidgets 是用于显示一些 QQuick 代码的小部件,用于 Widgets 应用程序。 But as you use a QQmlApplicationEngine, you are working in Quick.但是当您使用 QQmlApplicationEngine 时,您正在使用 Quick。 Your rootObject() won't be a QQuickWidget.您的rootObject()不会是 QQuickWidget。 So instead of looking for a QQuickWidget, access the engines rootContext - replace:因此,不要寻找 QQuickWidget,而是访问引擎 rootContext - 替换:

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

with

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

This will make your code a lot less prone to errors.这将使您的代码更不容易出错。

Also, in an unrelated note, you should always check your pointers, to make sure your static_cast went allright.此外,在不相关的注释中,您应该始终检查您的指针,以确保您的static_cast一切正常。 Otherwise you will get crashes if the engines rootObjects are empty or the first one is not a QQuickWidget.否则,如果引擎 rootObjects 为空或第一个不是 QQuickWidget,您将崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM