2016-05-04 30 views
0

我想在qt中實現自定義模型。程序崩潰與Qt QAbstractTableModel ::索引

我已將子類QAbstractTableModel轉換爲我自己的類。我已經重新實現了所需的方法,但不是索引方法(如docs所述)。 columnCount()總是返回4(有固定數量的列),而rowCount則返回insterted行的數量。

我的計劃看起來是這樣的:

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... 
} 

程序崩潰後,才試圖獲得m_model.index( 0,1)行,但不是一成不變的(即,接下來的幾行將執行,但幾秒鐘後程序崩潰)。當與我的調試器一起行時,程序會在故障線之後的線路上崩潰,或者在幾行之後崩潰,具體取決於我接通的速度。我得到這個錯誤信息:

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 

我想不通爲什麼當我要求的索引(0,0)和(1,0),而不是(0,1)中的程序工作正常。我也不知道爲什麼它不會立即失敗,而是需要幾秒鐘才能失敗。我沒有對線程做任何事情。

任何幫助,爲什麼我可能有這個問題或進一步的調試步驟,我可以採取將不勝感激。

我使用Qt 5.5,Qt Creator的3.4.2使用MinGW編譯

+0

我希望這個錯誤在'MyModel'中。 – drescherjm

回答

0

您試圖訪問無效索引...這是不確定的行爲...的qabstractitemmodel一些實現將返回如果索引無效參數很瘋狂。但它不能保證..

在這種情況下發生的事情是,表模型使用引擎蓋下的QList,並且不打擾範圍檢查......這會導致出界限訪問。我懷疑不受限制的訪問是一個undefined behavior,即使Qt沒有說明它是什麼。

無論如何這是錯誤的。 僅訪問有效索引。故事的結局。