如何在按下按钮时在Qt表格视图中自动选择下一行?

How to select next row automatically in Qt tableView whenever a pushbutton is pressed?

本文关键字:选择 一行 视图 按钮 Qt 表格      更新时间:2023-10-16

我有一个Qt tableView,它从SQLite数据库加载数据,我已经以这样一种方式配置它,即在默认视图中,自动选择第一行,我可以通过按按钮"呈现">对该行执行查询。现在,我希望我的程序在第一次按下"按钮"后自动选择下一行,以便当我第二次按"呈现"时,查询将在第二行执行。因此,基本上,每当按下按钮直到到达行号末尾时,我都想更改行的选择

我已经搜索了不少网站来寻找解决方案,但我无法找到解决我的问题的网站。

用于查看表s_info并选择第一行作为默认值的代码。

void table::on_view_clicked() 
{
MainWindow conn;
QSqlQueryModel * modal = new QSqlQueryModel();
conn.connOpen();
QSqlQuery* qry= new QSqlQuery(conn.info);
qry->prepare("Select Name,Roll_No from s_info order by Roll_no");
qry->exec();
modal->setQuery(*qry);
ui-> tableView ->setModel(modal);
ui->tableView-> setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->selectRow(0);
ui->tableView->setFocus();
conn.connClose();
qDebug()<< (modal->rowCount());
}

单击按钮名称"Present"时执行查询的代码。请注意,我已经根据s_info表中的列Roll_No执行了查询,第一行的卷号索引为(0,1)

void table::on_present_clicked()
{
QAbstractItemModel *model = ui->tableView->model();
QModelIndex index = model->index(0,1);
QString roll= (index.data().toString());
MainWindow conn;
conn.connOpen();
QSqlQuery qry;
QSqlTableModel modal;
qry.prepare("Update s_info set Present_Days=Present_Days + 1 where 
Roll_No='"+roll+"'");
qry.exec();
conn.connClose();
}

我希望当我第二次单击礼物时,行选择将移至第二行,并在该行上执行查询。我希望这种情况发生,直到我到达行数的末尾。

以下示例说明了您将要实现的目标。关键是您将需要一个QItemSelectionModel,它管理您的选择。很多时候,人们忘记将QItemSelectionModel的模型显式设置为视图的模型。

现在,如果要在表视图中选择一行,则"下一步"按钮将选择下一行。选择下一行基本上意味着选择下一行中的所有列。

如果您使用的是类似QSqlTableModel的东西,则用法应该相同,这并不重要。

#include <QApplication>
#include <QTableView>
#include <QPushButton>
#include <QHBoxLayout>
#include <QStandardItemModel>
#include <QItemSelectionModel>
int main(int argc, char** args) {
QApplication app(argc, args);
auto frame = new QFrame;
frame->setLayout(new QHBoxLayout);
auto tableView = new QTableView;
tableView->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection);
tableView->setSelectionBehavior(QAbstractItemView::SelectionBehavior::SelectRows);
auto model = new QStandardItemModel;
tableView->setModel(model);
auto selectionModel = new QItemSelectionModel;
selectionModel->setModel(model);
tableView->setSelectionModel(selectionModel);
frame->layout()->addWidget(tableView);
auto button = new QPushButton("Next");
frame->layout()->addWidget(button);
model->setRowCount(10);
model->setColumnCount(10);
frame->show();
QObject::connect(button, &QPushButton::clicked, [&]()
{
auto indices = selectionModel->selectedIndexes();
if (indices.isEmpty()) return;
QModelIndexList empty;
selectionModel->select(QModelIndex(), QItemSelectionModel::SelectionFlag::Clear);
for (auto index : indices)
{
auto newIndex=index.sibling(index.row() + 1, index.column());
selectionModel->select(newIndex,QItemSelectionModel::SelectionFlag::Select);
}
});
app.exec();
}