Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

c++ - How do I get the items selected from a QListView?

{
...
    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    
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I just tested this for my own needs and it works in Qt 5.1.

I'm pretty new to C++ so in this line:

foreach(const QModelIndex &index, list){

I don't know if the const and the dereferencing (&) is needed - it works with or without. I cobbled this together from various examples I've seen.

Perhaps someone who understands C++ better can comment.

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(",");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...