【问题标题】:QT Quick Application Window embed C++ objectQT Quick Application Window 嵌入 C++ 对象
【发布时间】:2025-12-10 17:20:03
【问题描述】:

我有一个 QT Quick 2.2 ApplicationWindow,我想在这个 ApplicationWindow 中使用一个 C++ 对象。

我知道QQuickView 视图,但这仅适用于派生自QQuickItem 的对象(不适用于ApplicationWindow)。

我也知道qmlRegisterType,但这只会在 QML 中添加一个通用的 C++ 类。我只想在ApplicationWindow 中有一个 C++ 对象(在 C++ 代码中实例化)。

是否有可能在 QT Quick 2.2 ApplicationWindow 中使用 C++ 对象?

main.cpp

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQmlContext>
#include "myclass.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    MyClass myClass;

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

    return app.exec();
}

myclass.h

#include <QObject>
#include <QString>

class MyClass  : public QObject
{
    Q_OBJECT
public:
    MyClass(QObject *parent = 0) {};
    Q_INVOKABLE QString getValue();
};

myclass.cpp

#include "myclass.h"
#include <QString>

QString MyClass::getValue() {
    return "42";
}

qrc:///main.qml

import QtQuick 2.2
import QtQuick.Controls 1.1

ApplicationWindow {
    visible: true

    Text {
        text: myClass.getValue()
        anchors.centerIn: parent
   }
}

谢谢

【问题讨论】:

  • 了解qmlRegisterType
  • 另外:qt-project.org/doc/qt-5/qtqml-cppintegration-topic.html 这个问题在这里已经讨论过很多次了,虽然我找不到一个类似的会被认为是重复的......
  • 根据您的更新,您可以在我的回答中选择我的第二个解决方案。

标签: c++ qt qtquick2


【解决方案1】:

这取决于你的目的。如果你想define QML type from C++,,你应该在你的 main.cpp 中这样做:

qmlRegisterType< MyClass >("com.example.myclass", 1, 0, "MyClass");

现在在您的 .qml 文件中,首先您需要使用 import 语句导入新创建的数据类型:

import com.example.myclass 1.0

然后你可以从你自己的数据类型创建一个项目:

import QtQuick 2.2
import QtQuick.Controls 1.1
import com.example.myclass 1.0

ApplicationWindow {
    visible: true

    Text {
        text: myClass.getValue()
        anchors.centerIn: parent
   }
    MyClass {

   }

}

但是你有另一个解决方案。您可以将 QObject 对象从 c++ 传递到 QML。

QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("myClass", new MyClass);
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

现在您可以在 qml 文件中访问 myClass 对象。

【讨论】:

  • 你的第二个解决方案就是我想要的。这次真是万分感谢。但是我还有一个小问题,我进入控制台'ReferenceError:myClass is not defined'。
  • setContextProperty 必须在 engine.load 之前
  • @saeed 你能改变你的解决方案 engine.load... 和 engine.rootContext... ,如果有人有同样的问题。感谢您的帮助。
  • @user3734670 之前做过 :)