Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Determine single selected row in a table view



  • I have a table view that's set for Extended Selection. Is the following correct code to determine if a single row is selected, and if so which row number it is? If correct is this the "best way" or is there a better way to do it?

    //Assume that the following has been done:
    //	connect(ui->tableView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(tableViewItemClickedEvent(const QModelIndex&)));
    
    void StackingDlg::tableViewItemClickedEvent(const QModelIndex& index)
    {
    	qDebug() << "Table View item clicked, row " << index.row();
    	QItemSelectionModel * qsm = ui->tableView->selectionModel();
    	QModelIndexList selectedRows = qsm->selectedRows();
    	//
    	// If only one row is selected, we want to know the filename
    	//
    	if (1 == selectedRows.count())
    	{
    		QModelIndex& index = selectedRows[0];
    		if (index.isValid())
    		{
    			const DSS::ImageListModel* model = dynamic_cast<const DSS::ImageListModel*>(index.model());
    			int row = index.row();
    			m_strShowFile = model->selectedFileName(row);
    		}
    	}
    }
    


  • Very close. QModelIndexList selectedRows = qsm->selectedRows(); should be QModelIndexList selectedRows = qsm->selectedIndexes();



  • Please could you explain why QItemSelectionModel::selectedRows() isn't correct? Or put another way - what's the crucial difference?

    PS the code I have to set up the table view reads:

            tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
            tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    


  • @Perdrix said in Determine single selected row in a table view:

    PS the code I have to set up the table view reads:
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    Given this I think your use of selectedRows() is correct. Maybe not knowing that affected @VRonin's answer.



  • @Perdrix said in Determine single selected row in a table view:

    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    In this case they are equivalent.

    The doc explains the difference pretty well:

    QModelIndexList QItemSelectionModel::selectedRows(int column = 0) const
    Returns the indexes in the given column for the rows where all columns are selected.

    So if you selected a single cell in a row selectedRows would not return it


Log in to reply