无法在 QML 列表视图中调用 Qt c++ 方法



我有一个充当ListView的qml模型的QObjects列表。我可以更改它们的属性,但不能调用任何slots或Q_INVOKABLE方法。这是我的问题的最小例子(遗憾的是它仍然很大)。

定义一个具有属性和可调用方法的非常简单的类


// DummyObject.h
class DummyElem : public QObject
{
Q_OBJECT
Q_PROPERTY(QString dummy READ getDummy CONSTANT)
public:
explicit DummyElem(QObject *parent = nullptr);
QString getDummy();
Q_INVOKABLE void notifyStuff();
};
实现这个简单类的琐碎方法
// DummyObject.cpp
#include "DummyElem.h"
#include <QDebug>
DummyElem::DummyElem(QObject *parent) : QObject(parent) {}
QString DummyElem::getDummy() {return "lorem";}
void DummyElem::notifyStuff() {qDebug() << "ipsum";}
以列表作为根属性启动qml应用程序。完全是从教程中复制粘贴的,他们在教程中称之为q_incoable方法。
// main.cpp
#include "DummyElem.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QList<QObject*> dataList;
dataList.append(new DummyElem);
dataList.append(new DummyElem);
QQmlApplicationEngine engine;
QQmlContext* context = engine.rootContext();
context->setContextProperty("dataModel", QVariant::fromValue(dataList));
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
描述一个带有ListView的qml布局和一个在单击时将调用c++方法的委托。
// main.qml
import QtQuick 2.7
import QtQuick.Window 2.2
Window {
visible: true
ListView {
anchors.fill: parent
model: dataModel
delegate: Component {
Text {
text: model.dummy
MouseArea {
anchors.fill: parent
onClicked: {model.notifyStuff()}
}
}
}
}
}

这个问题很难调试,因为c++类模型不能被json strigified,我也不能获得它的javascript entries()。我得到的错误是"未定义不是函数",这也很酷。我尝试在QML中注册Qt类型,但这也没有起到任何作用。我使用的是Qt库版本5.9.4,但QtCreator中的"最低Qt版本要求"框设置为"Qt 5.6"。

您需要使用modelData。我不完全确定为什么,很可能是因为QVariantList。你可以在这一页上多读一些。

Window {
visible: true
ListView {
anchors.fill: parent
model: dataModel
delegate: Component {
Text {
text: modelData.dummy
MouseArea {
anchors.fill: parent
onClicked: modelData.notifyStuff();
}
}
}
}
}

有趣的事实:这是我在Qt 5.11.3:上得到的错误

TypeError: Property 'notifyStuff' of object QQmlDMObjectData(0x5585fe567650) is not a function

至少比undefined更能说明问题,但我想说的是,仍然不是完全描述性的。

最新更新