2013-08-07 4 views
7
{ 
... 
    nrow = 10;  
    ncol = 1; 

    /*create QListView */ 
    m_listView = new QListView(this); 
    m_listView->setGeometry(QRect(QPoint(0,100), QSize(100, 150))); 

    QStandardItemModel *model = new QStandardItemModel(nrow, 1, this); 

    //fill model value 
    for(int r=0; r<nrow; r++) 
    { 
     QString sstr = "[ " + QString::number(r) + " ]"; 
     QStandardItem *item = new QStandardItem(QString("Idx ") + sstr); 
     model->setItem(r, 0, item); 
    } 

    //set model 
    m_listView->setModel(model); 
    m_listView->setSelectionMode(QAbstractItemView::ExtendedSelection); 
    connect(m_listView, SIGNAL(pressed(QModelIndex)), this, SLOT(hItem(QModelIndex))); 
} 

void MainWindow::hItem(QModelIndex m) 
{ 
    QItemSelectionModel *selectionModel = m_listView->selectionModel(); 

    m_txt2->setText(QString::number(selectionModel->selectedIndexes().at(0),'d',0));//??? 

    //not sure how to get the items selected: index and string per selection  
} 

답변

18

난 그냥 내 자신의 필요에 대한이 테스트하고 Qt 5.1에서 작동합니다. const와 역 참조 (&)가 필요한 경우 나도 몰라

foreach(const QModelIndex &index, list){ 

- 그와 함께 또는없이 작동 :

나는이 줄 수 있도록 ++ C 꽤 새로운 해요. 내가 본 여러 사례에서이 사실을 모아 봤습니다.

아마도 C++을 더 잘 이해하는 사람이 댓글을 쓸 수 있습니다.

void MainWindow::on_keywordsList_clicked(const QModelIndex &index) 
{ 
    QModelIndexList list =keywordListView->selectionModel()->selectedIndexes(); 

    QStringList slist; 
    foreach(const QModelIndex &index, list){ 
     slist.append(index.data(Qt::DisplayRole).toString()); 
    } 
    qDebug() << slist.join(","); 
} 
+3

const ref가 더 좋습니다. & 그것을 빨리하면, const는 원래 컨테이너의 의도하지 않은 수정에 대해 안전합니다. –