在QML中公开基类函数

时间:2019-05-27 21:57:27

标签: c++ qt qml

我正在尝试调用在基类中声明的函数,但无法从 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);
}

main.qml

function toggleCameraView(){
    g.toggleCameraView()
}

这给了我错误:

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

2 个答案:

答案 0 :(得分:0)

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

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

main.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"

main.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

答案 1 :(得分:0)

function toggleCameraView(){
    g3.toggleCameraView()
}

为什么是“ g3”?它应该是“ g”,与ctxt->setContextProperty("g", this);

中的名称相同