2011-03-21 22 views
4

看來我的QListView - > QAbstractListModel的選擇支持零內置選擇。我是否必須從頭開始編寫所有內容?在UI中捕獲選擇事件,模型項目標記爲選中狀態等?似乎沒有對此的開箱即用支持。如何檢測QListView中的行選擇<- >使用Item委託的QAbstractListModel?

奇怪的是有一個QItemSelectionModel確實支持這個,但是你不能在QListView中使用它,因爲它不是從QAbstract派生的...。

我的模型類應該使用多繼承來繼承QItemSelectionModel和QAbstractListModel嗎?否則,我不知道如何避免自己重寫這個功能。

我的最終目標是繪製我的項目以確定是否選中該項目的代理,無論是在paint和sizeHint函數中。

回答

6

而QListView從QAbstractItemView中,其中有一個方法來獲得選擇模型得出:

QItemSelectionModel *selectionModel = myView->selectionModel(); 

這個方法返回一個指向選擇模型,這是長期存在的,也就是說,你可以保存指針,連接到它的信號等

0

由丹尼爾給出的答案是正確的,但它是更好地適合初學者一個例子來說明吧:

class MyCustomModel : public QAbstractListModel 
{ 
    Q_OBJECT 
public: 
    ImageCollectionModel(QObject *parent, MyCustomCollection *data); 
     : QObject(parent) 
     , m_myData(data) 
    { 
    } 

public slots: 
    void onSelectedItemsChanged(QItemSelection selected, QItemSelection deselected) 
    { 
     // Here is where your model receives the notification on what items are currently 
     // selected and deselected 
     if (!selected.empty()) 
     { 
      int index = selected.first().indexes().first().row(); 
      emit mySelectedItemChanged(m_myData->at(index)); 
     } 
    } 

signals: 
    void mySelectedItemChanged(MyCustomItem item); 

private: 
    MyCustomCollection *m_myData; 

    // QAbstractItemModel interface 
public: 
    int rowCount(const QModelIndex &) const override; 
    QVariant data(const QModelIndex &index, int role) const override; 
}; 

當您將自定義模型傳遞給QListView時,這是連接它的好機會:

ui->myListView->setModel(m_myModel); 
connect(ui->myListView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), 
     m_myModel, SLOT(onSelectedItemsChanged(QItemSelection, QItemSelection))); 
相關問題