How to edit selected data/row in QTableView?

658 views Asked by At

I have a QTableView and if a user selected a row, i want to change the data in the table by clicking a button. So my problem is, that I don't know how to get the rowindex of the selected row, to give this to the button.

I have this Dialog:

ListDialog::ListDialog(QWidget *parent, int listId) :
    QDialog(parent),
    ui(new Ui::ListDialog)
{
    ui->setupUi(this);

    DbManager conn;
    model = new QSqlQueryModel();
    conn.connOpen();
    QSqlQuery* query = new QSqlQuery(conn.mydb);
    QSqlQuery* query2 = new QSqlQuery(conn.mydb);

    query->prepare("SELECT f.name AS Name, f.quantityperpack AS Menge_pro_Pack, f.unit AS Einheit, c.amount AS Menge FROM Contains c, Food f WHERE c.ListId=:listId AND c.FoodId = f.FoodId");
    query->bindValue(":listId", listId);
    query->exec();
    model->setQuery(*query);
    ui->tableView->setModel(model);


    query2->prepare("SELECT name FROM lists WHERE ListId=:listId AND c.FoodId");
    query2->bindValue(":listId", listId);
    query2->exec();
    query2->next();
    ui->textBrowser ->setText(query->value(0).toString());

    conn.connClose();
}

And when I click on this button it should change the value

void ListDialog::on_pushButton_plus_clicked(){
    //get Index of selected Row
    //add 1 to the amount column in this row
}

I'm new in qt so thanks for your help.

1

There are 1 answers

0
Brushman On

To answer your question "how to get the row-index of the selected row" in your button handling code add something like:

QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if( indexes.count() > 0 ){
    // indexes[0].row()     // will return the row-index of the first selected row
}

To ensure that only one row can be selected at a time setup the tableView with:

ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);