在 qml 中公开基类函数
Expose a base class function in 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);
}
主.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);
中是同名
相关文章:
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 将自定义函数传递到基抽象类中以延迟执行
- 调用原子的 store() 时可以调用基类型类的函数吗?C++
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 从基类调用函数的多态性
- 在成员构造函数之后调用基类构造函数
- 在C++单元测试上下文中,抽象基类是否应将其他抽象基类作为函数参数
- 如何在将原始指针移动到基类构造函数之前从unique_ptr中提取原始指针
- 如何在具有相同函数名称的派生类中调用基类的函数
- 我不能访问基类的函数
- 根据模板参数引用不同基类的函数
- 在基/派生类中调用C++的纯虚函数
- C++ 模板化基类的函数模板专用化
- 如果基类指针无法访问派生类成员函数,那么多态性有什么方便的呢?
- 如何在C++中调用基类虚函数
- 指向从指针派生类成员函数的指针,指向基类成员函数
- C++:在共享对象中调用抽象基类构造函数/未定义的符号
- 如何在 C++ 中将参数传递给基类构造函数