簡體   English   中英

無法在QML ListView中調用Qt C ++方法

[英]Can't invoke Qt c++ method in QML ListView

我有一個QObjects列表,用作ListView的qml模型。 我可以更改其屬性,但不能調用任何插槽或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();
    };
實現這個簡單類的簡單方法
    // 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()}
                    }
                }
            }
        }
    }

使用列表作為根屬性啟動qml應用程序。 完全是從教程中復制粘貼的,他們在其中將其稱為q_incokable方法。
  // 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 entry()。 我得到的錯誤是“未定義不是函數”,這也是很酷的。 我嘗試在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更具說服力,但我要說的還不夠全面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM