在 qml 中公开基类函数

Expose a base class function in qml

本文关键字:基类 类函数 qml      更新时间:2023-10-16

我正在尝试调用在基类中声明的函数,但我无法从 QML 调用,这是我的代码示例

R.cpp

class R
{
public:
    virtual void startGui() = 0;
    void  toggleCameraView();
};
void R::toggleCameraView(){
  //do stuff
}

G.cpp

class G : public R
{
    Q_OBJECT
public:
  void startGui();
};
void G::startGui(){
  QQmlContext *ctxt = engine.rootContext();
  ctxt->setContextProperty("g", this);
}

主.qml

function toggleCameraView(){
    g.toggleCameraView()
}

这给了我错误:

TypeError: Property 'toggleCameraView' of object G(0x2838a8) is not a function

因为您没有提供 MCVE,所以我不会指出有关您的代码的错误原因。相反,我将展示一个可行的示例。

如果您希望从 QML 访问一种方法,则必须是插槽或Q_INVOKABLE,我将在我的示例中使用最后一种方法:

主.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QDebug>
class R: public QObject
{
    Q_OBJECT
public:
    using QObject::QObject;
    virtual void startGui() = 0;
    Q_INVOKABLE void  toggleCameraView();
};
void R::toggleCameraView()
{
    qDebug() << __FUNCTION__;
}
class G: public R
{
public:
    G(QObject *parent=nullptr): R(parent){
        startGui();
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        engine.load(url);
    }
    void startGui() override;
private:
    QQmlApplicationEngine engine;
};
void G::startGui()
{
    QQmlContext *ctxt = engine.rootContext();
    ctxt->setContextProperty("g", this);
}
int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    G g;
    return app.exec();
}
#include "main.moc"

主.qml

import QtQuick 2.12
import QtQuick.Window 2.12
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    Component.onCompleted: g.toggleCameraView()
}

输出:

toggleCameraView
function toggleCameraView(){
    g3.toggleCameraView()
}

为什么"G3"?应该是"G",在ctxt->setContextProperty("g", this);中是同名