【问题标题】:SortFilterProxyModel in Qt with qml modelQt 中的 SortFilterProxyModel 与 qml 模型
【发布时间】:2016-07-20 07:48:07
【问题描述】:

我对 QT 的表模型/视图的 sortFilterProxyModel 有疑问。

当我从 QML 中由 model(ListModel) 填充的表中键入要搜索的单词时,它排序正确并且结果也相应地(如文件的正确名称和它的 Id )但是当我单击该行时获取索引,它从零开始显示内容,因为它具有重新索引的属性,但我不希望因为它重新索引我收到错误的fileId,因为我设置了。

我被这个问题困住了。我怎么能把它排除在外?

【问题讨论】:

  • 不确定我是否理解正确,但有:QSortFilterProxyModel::mapToSource(QModelIndex index)
  • 不使用这个,因为我使用的是 Qml,所以 sortFilterProxyModel 直接在那里使用。和方法 "QObject *SortFilterProxyModel::source() const //PNU { //qDebug()
  • 这个答案在这里stackoverflow.com/questions/34252413/… 怎么样?不知道你用的是什么编程语言。该链接适用于python。但是,你可以有一个想法。

标签: qt qml qsortfilterproxymodel


【解决方案1】:

我遇到了同样的问题,并通过这样做来解决问题:

在你的 sortfilterproxy.h 添加一个公共槽函数:

public slots:
    int getModelIndex(int);

在你的 sortfilterproxy.cpp 中实现这个函数:

int SortFilterProxyModel::getModelIndex(int row)
{
     QModelIndex sourceIndex = mapToSource(this->index(row, 0));
    return sourceIndex.row();//this returns an integer
}

现在您可以在 QML 中的 TableView 上执行此操作:

  onCurrentRowChanged: 
  {
   var currentIndex = currentRow;
   console.log(currentIndex);
   var rowModelIndex= proxyModel.getModelIndex(currentIndex);
   console.log(rowModelIndex);
...

希望这会有所帮助。

迈克尔

【讨论】:

  • 谢谢,这对我有用,但是我很困惑为什么这是必要的。 mapToSource(index) 应该提供相同的功能,但对我不起作用。
【解决方案2】:

遇到了和你一样的问题。 玩弄 QtQuick TableView 示例Qt Blog note

我找到了QTBUG-50019(TableView:按项目而不是按索引跟踪选择)。 好像不会很快解决。

作为替代方案,您可以在表格/列表视图中创建一个额外的索引,并像这样为自己的目标调整它们

ListView {
    id: root

    property real selectedIndex: -1
    ...
    delegate: Item {
            color: (index === root.selectedIndex) 
                   ? parent.color = "gray" 
                   : parent.color = root.color

            Connections {
                target: root

                onSelectedIndexChanged: {
                    if(index === root.selectedIndex)
                        root.currentIndex = index
                }
            }

            MouseArea {
                anchors.fill: parent
                onClicked: root.selectedIndex = index
            }
     }
}

【讨论】:

  • 感谢@Alex Makarov,您的建议。但是我确实通过分配与 fileId 列相同的角色来解决它,所以现在每当我单击按钮打开文件时,它都会选择正确的 fileId,现在我不需要获取它的索引
  • 您应该将您的解决方案添加为对原始问题的更新,并使该主题对其他人更有用。
猜你喜欢
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多