如何从QListView中获取所选项目

How do I get the items selected from a QListView?

本文关键字:选项 项目 获取 QListView      更新时间:2023-10-16
{
...
    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    
}

我只是根据自己的需要测试了它,它在Qt 5.1中有效。

我对C++还很陌生,所以在这一行:

foreach(const QModelIndex &index, list){

我不知道是否需要const和取消引用(&)——不管有没有,它都能工作。我从我看到的各种例子中拼凑而成。

也许更了解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(",");
}