【问题标题】:How to access ListView's current item from qml如何从 qml 访问 ListView 的当前项
【发布时间】:2013-04-29 16:22:26
【问题描述】:

我有一个存储和编辑笔记的应用程序。笔记列表显示在列表视图中,如下所示:

Page {
        id: noteList
        title: i18n.tr("QNote")
        visible: false

        Column {
            anchors.fill: parent

            ListView {
                anchors.fill: parent
                model: notes
                delegate: ListItem.Standard {
                    text: Title
                    onClicked: editNote(NoteText, Title, modelData);
                    progression: true
                }
            }
        }
    }

function editNote(text, title, item) {
    pageStack.push(noteEdit, {title: title, text: text});
    handler.setActiveItem(item);
}

notes 项目是一个 NoteListModel,它是 QAbstractListModel 的子类,并包含 NoteListItems。我想做的是存储当前选择的 NoteListItem ,这样当用户想要保存修改后的笔记时,我可以轻松地访问里面的 Note 对象。但是,我不知道如何从 qml 委托访问支持的 NoteListItem。 modelData 似乎是别的东西。有什么办法吗?如果我可以将 Note 对象包装在 QVariant 中,我可以通过角色轻松访问它,但是当我像这样尝试时

QVariant NoteListItem::data(int role) {
    switch (role) {
    case Title:
        return note.getTitle();
    case NoteText:
        return note.getText();
    case NoteObject:
        return QVariant::fromValue(note);
    default:
        return QVariant();
    }
}

导致编译器错误提示

qmetatype.h:642:错误:“sizeof”对不完整类型“QStaticAssertFailure”的无效应用

或者我应该尝试从支持代码访问选定的列表项吗?有什么办法吗?你有什么想法吗?

感谢您的宝贵时间。问候, 彼得

【问题讨论】:

标签: qt qml qt5 qabstractitemmodel


【解决方案1】:

这花了我很长时间才找到,因为 Stackoverflow 上有很多不正确的解决方案。

纯粹的 QML 方式是使用 DelegateModel 并从 QML 访问它,如下所示:

import QtQuick 2.4
import QtQml.Models 2.1

ListView {
    property var currentSelectedItem

    onCurrentItemChanged{
            // Update the currently-selected item
            currentSelectedItem = myDelegateModel.items.get(currentIndex).model;
            // Log the Display Role
            console.log(currentSelectedItem.display);
    }

    model: DelegateModel {
        id: myDelegateModel
        model: myAbstractItemModel
        delegate: {
            // Define delegates here
        }
    }
}

此行返回一个对象 (var),您可以像在委托中一样访问它: myDelegateModel.items.get(currentIndex).model

此示例假设您仅使用默认的 DelegateModelGroup。

http://doc.qt.io/qt-5/qml-qtqml-models-delegatemodel.htmlhttp://doc.qt.io/qt-5/qml-qtqml-models-delegatemodelgroup.html#get-method方法

【讨论】:

  • 非常感谢!有许多当前的答案涉及非常繁琐的解决方法,例如在模型实现中手动实现 get 方法,使用自定义通知器和其他混乱。这是一个干净的内置解决方案,可以正常工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 2016-12-08
  • 1970-01-01
相关资源
最近更新 更多