简体   繁体   中英

Program Crashes with Qt QAbstractTableModel::index

I am trying to implement a custom model in qt.

I have subclassed QAbstractTableModel into my own class. I have reimplemented the needed methods, but not the index method (as the docs say). columnCount() always returns 4 (there are a fixed number of columns) and rowCount returns the number of insterted rows.

My program looks something like this:

application.h

#include mymodel.h
class ContilasSimulator : public QApplication
{
public:
    Aplication(int argc, char *argv[]);
    void someFunction();
private:
    MyModel m_model;
    MainWindow m_window;
};

application.cpp

#include application.h
Application::Application(int argc, char *argv[]) : QApplication(argc,argv),
{
    m_window.setModel(&m_model);
}

void someFunction()
{
    //...
if (m_model.insertRows(0,2))
    {
        QModelIndex index = m_model.index(0,0); //this statement works fine
        index = m_model.index(1,0); // this statement also works fine
        index = m_model.index(0,5); //this statements return an invalid index (as expected)
        index = m_model.index(0,1); //the program crashes a few seconds after executing this line
        //other code...
}

The program crashes only after I have tried to get the m_model.index(0,1) line, but not immidiately (ie, the next few lines will execute, but a few seconds later the program crashes). When going line by line with my debugger, the program will crash either on the line after the probelm line, or a few lines later, depending on how fast I step through. I get this error message:

ASSERT failure in QList<T>::at: "index out of range", file C:\Qt\Qt5.5.1\5.5\mingw492_32\include/QtCore/qlist.h, line 510

I cannot figure out why the program works fine when I am requesting an index of (0,0) and (1,0) but not (0,1). Nor can I figure out why it does not fail right away and instead takes a few seconds to fail. I am not doing anything with threads.

Any help on why I might have this problem or further debugging steps I can take would be greatly appreciated.

I am using Qt 5.5 with Qt Creator 3.4.2 compiling with mingw

You are trying to access invalid indexes... This is unspecified behavior... Some implementations of qabstractitemmodel will return an invalid index if the parameters are crazy. But it is not guaranteed..

What happen in this case is that the table model use a QList under the hood and don't bother doing range checks... which cause an out of bound access. I suspect out of bound accesses to be an undefined behavior , even if Qt doesn't say what it is.

Anyway it is wrong. Access valid indexes only . End of the story.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM