如何以编程方式选择QTableView中的下一行

How to select next row in QTableView programmatically

本文关键字:一行 编程 方式 QTableView 选择      更新时间:2023-10-16

我有一个QTableView子类,我正在标记它并用这个保存它的状态:

connect(this,
        SIGNAL(clicked(const QModelIndex &)),
        this,
        SLOT(clickedRowHandler(const QModelIndex &))
    );
void PlayListPlayerView::clickedRowHandler(const QModelIndex & index)
{
    int iSelectedRow = index.row();
    QString link = index.model()->index(index.row(),0, index.parent()).data(Qt::UserRole).toString();
    emit UpdateApp(1,link );
}

现在我喜欢用程序将所选内容移动到下一行(而不是用鼠标按行)并调用clickedRowHandler(...),我该怎么做?感谢

您已经有了当前行索引,所以使用以下内容来获取下一行的模型索引

QModelIndex next_index = table->model()->index(row + 1, 0);

然后您可以使用将该模型索引设置为当前模型索引

table->setCurrentIndex(next_index);

显然,你需要确保你没有跑过表的末尾,而且可能还有一些额外的步骤来确保整行都被选中,但这应该会让你更接近。

/*
 * selectNextRow() requires a row based selection model.
 * selectionMode = SingleSelection
 * selectionBehavior = SelectRows
 */
void MainWindow::selectNextRow( QTableView *view )
{
    QItemSelectionModel *selectionModel = view->selectionModel();
    int row = -1;
    if ( selectionModel->hasSelection() )
        row = selectionModel->selection().first().indexes().first().row();
    int rowcount = view->model()->rowCount();
    row = (row + 1 ) % rowcount;
    QModelIndex newIndex = view->model()->index(row, 0);
    selectionModel->select( newIndex, QItemSelectionModel::ClearAndSelect );
}