在Qt中,您可以使用QML和C++相互调用。为了实现这一目标,您需要执行以下步骤:
// MyClass.h
#include <QObject>
class MyClass : public QObject
{
Q_OBJECT
public:
explicit MyClass(QObject *parent = nullptr);
public slots:
QString myFunction();
};
// MyClass.cpp
#include "MyClass.h"
MyClass::MyClass(QObject *parent) : QObject(parent)
{
}
QString MyClass::myFunction()
{
return "Hello from C++!";
}
main.cpp
文件中,使用qmlRegisterType
函数注册类:// main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "MyClass.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
qmlRegisterType<MyClass>("com.example", 1, 0, "MyClass");
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);
return app.exec();
}
main.qml
文件中导入C++类:// main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import com.example 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Call C++ Function from QML")
MyClass {
id: myClassInstance
}
Button {
text: "Call C++ function"
onClicked: {
console.log(myClassInstance.myFunction())
}
}
}
现在,当您运行QML应用程序并单击按钮时,它将调用C++函数并在控制台中显示结果。