2

我一直在寻找解决这个问题的方法,我开始相信这可能是 Qt 函数本身的一个错误。问题是,在您调用 QItemSelectionModel::selectedIndexes() 后,当程序尝试破坏此函数返回的 QModelIndexList 时,程序将崩溃。在崩溃之前,您会收到以下调试消息:

调试断言失败!
(...)
文件:f:\dd\vctools\crt_bld\self_x86\crt\src\dbgheap.c
行:1419
表达式:_pFirstBlock == pHead
(...)

下面是最简单的会导致问题的代码,大家可以自己测试一下:

#include <QApplication>
#include <QStringList>
#include <QStringListModel>
#include <QItemSelectionModel>
#include <QModelIndex>
#include <QModelIndexList>
#include <QListView>
#include <QItemSelectionModel>

void doSomethingWithSelection(QItemSelectionModel* selectionmodel);

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QStringList list;
    list.push_back("1");
    list.push_back("2");
    list.push_back("3");
    list.push_back("4");
    QStringListModel model(list);
    QListView view;
    view.setModel(&model);
    view.setSelectionMode(QAbstractItemView::ExtendedSelection);

    QItemSelectionModel *selectionmodel = view.selectionModel();
    QModelIndex first = model.index(0);
    QModelIndex last = model.index(2);
    QItemSelection selection(first, last);
    selectionmodel->select(selection,QItemSelectionModel::Select);

    doSomethingWithSelection(selectionmodel);

    view.show();
    return a.exec();
}

void doSomethingWithSelection(QItemSelectionModel* selectionmodel)
{
    QModelIndexList indexlist = selectionmodel->selectedIndexes();
    // this is what causes the error. I put this inside a function
    // so the error will happen when exiting the function,
    // when the program try to destroy the list nodes.
}
4

3 回答 3

1

我在QTreeView访问和访问selectedIndexes()selectionModel().

当我使用正确的编译器开关和正确的库时,它已修复。/MDQt

要修复崩溃:

  • 编译你的代码/MDd并与调试链接Qt libs(例如Qt5Cored.lib
  • 编译您的代码/MD并与发布链接Qt libs(示例Qt5Core.lib
于 2019-08-30T02:46:40.800 回答
1

我有完全相同的问题,只是我使用选定的行而不是选定的索引。当 QModelIndexList 中的内部 QList 尝试从堆中删除索引时,我将其缩小到函数退出。不知道如何修复它,但我在这里阅读了这篇有趣的帖子并提出了这个功能:

QModelIndexList Class::getViewSelection(QAbstractItemView *view ,  int columnNumber) const
{
  QModelIndexList list;
  for (int row = 0; row < view->model()->rowCount(view->rootIndex()); ++row)
  {
    QModelIndex index = view->model()->index(row, columnNumber, view->rootIndex());

    if (view->selectionModel()->isSelected(index))
        list.push_back(index);
   }
  return list;
}

我编写了这个函数来获取选定的行,因此列参数是您想要索引的列。

于 2015-08-11T08:20:40.957 回答
0

我设法解决了这个问题,但现在我不明白为什么会这样,但是:(我写这个作为答案希望它可以帮助有同样问题的人)

在我的 Qt 项目中,我使用带有Microsoft Windows SDK for Windows 7 (7.0.7600.16385.40715) (x86)的工具包作为编译器。当我将编译器更改为Microsoft Visual C++ Compiler 10.0 (x86)时,此代码可以正常工作。

正如我所说,我不知道为什么会这样,如果有人可以向我解释这一点,我会很高兴听到。我什至不知道为什么 Windows SDK 被列为编译器。它不是,是吗?

于 2013-02-28T08:48:09.473 回答