2013-02-27 97 views
4

我已經創建了一個非常簡單的例子QListView與自定義QAbstractListModel。顯示QListView,但它是空的。QListView與QAbstractListModel顯示一個空列表

我在做什麼錯?

代碼:

#include <QListView> 
#include <QAbstractListModel> 
#include <QApplication> 

class DataModel: public QAbstractListModel 
{ 
public: 
    DataModel() : QAbstractListModel() {} 
    int rowCount(const QModelIndex & parent = QModelIndex()) const { return 2; } 
    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const 
    { 
     return "a"; 
    } 
}; 

int main(int argc, char **argv) 
{ 
    QApplication app(argc, argv, true); 
    QListView *lv = new QListView(); 
    DataModel d; 
    lv->setModel(&d); 
    lv->show(); 
    app.setMainWidget(lv); 
    app.exec(); 
} 

謝謝!

的修復以前的代碼是模型的家長設置爲QListView

DataModel d(lv); 

但是,這提出了一個問題,哪裏是模型/視圖獨立性如果模型必須有一個參考以觀點?

如果我想在兩種不同視圖中使用此模型會怎麼樣?

回答

9

只有當role = Qt :: DisplayRole時,您的方法數據纔會返回「a」。否則,它會爲每個角色返回「a」。

所以,添加一個簡單的測試,它會工作:

QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const 
{ 
    if (role == Qt::DisplayRole) { 
     return "a"; 
    } 
    return QVariant(); 
} 
+0

完成,但它仍然沒有表現出任何項目:( – 2013-02-27 13:55:21

+1

重要的是,數據()返回無效的QVariant() 檢查。如果你沒有忘記「return QVariant()」 – 2013-02-27 14:22:54

+0

它確實返回QVariant()。我已經解決了它,儘管我仍然認爲它有錯誤,請看原版的 – 2013-02-28 07:07:35