How to get index[int] of current selected row from ListView in Qt with C++?



  • I am trying to delete row in my database, through Qt ListView. So in GUI window I have listView with some data. User select one row and after clicking 'delete button', the row is deleting from ListView and database. I have problem with getting the number of the row which the user selected. The program returning me value -1

    void MainWindow::on_pushButtonUsunWydatek_clicked()
    {
    connectionOpen(); // Open connection to the DB
    QSqlQueryModel model;

    int index = ui->listView_Wydatki->currentIndex().row(); //want to get current selected row by the user HERE is the main problem
    
    int id = model.record(index).value("id").toInt(); //here I collect specific ID from Database
    
    //here I check if it get well
    qDebug() << "ID: " << id;
    qDebug() << "Index: " << index;
    
    model.setQuery("DELETE FROM wydatki WHERE id = "id" "); // additional question: how to properly put 'id' variable here?
    
    connectionClose(); //closing connection with DB 
    

    }


  • Moderators

    @time said in How to get index[int] of current selected row from ListView in Qt with C++?:

    what does the following output?
    qDebug() << model.record(index).value("id")

    model.setQuery("DELETE FROM wydatki WHERE id = "id" "); // additional question: how to properly put 'id' variable here?

    There are multiple possible solutions. One can be model.setQuery( QString("DELETE FROM wydatki WHERE id = \"") + id + "\"" )



  • @raven-worx Thank you. And what with other problems? Especially with getting index of the selected row in ListView?
    I can't get the output qDebug() << model.record(index).value("id") because I don't have properly index. The program returning index -1



  • ui->listView_Wydatki->selectionModel()->selectedIndexes() will return a list of selected indexes. do not use currentIndex() as if you deselect an item current index will be that item


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.