我有一个QTableView,如果用户选择了一行,我想通过单击表中的一个按钮来更改表中的数据。所以我的问题是,我不知道如何获取所选行的rowindex,将其传递给按钮。
我有这个对话框:
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();
}
当我点击这个按钮时,它应该会改变这个值
void ListDialog::on_pushButton_plus_clicked(){
//get Index of selected Row
//add 1 to the amount column in this row
}
我是新来的,所以谢谢你的帮助。
发布于 2021-05-16 10:51:27
要在按钮处理代码中回答“如何获取所选行的行索引”的问题,请添加如下内容:
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if( indexes.count() > 0 ){
// indexes[0].row() // will return the row-index of the first selected row
}
要确保一次只能选择一行,请使用以下命令设置tableView
:
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
https://stackoverflow.com/questions/67486203
复制