【问题标题】:How to select next row in QTableView programmatically如何以编程方式在 QTableView 中选择下一行
【发布时间】:2020-09-08 01:07:01
【问题描述】:

我有 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(...) 我该怎么做? 谢谢

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    你已经有了当前行的索引,所以使用类似下面的方法来获取下一行的模型索引

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

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

    table->setCurrentIndex(next_index);
    

    显然,您需要确保您没有跑过表格的末尾,并且可能需要一些额外的步骤来确保选择了整行,但这应该会让您更接近。

    【讨论】:

    • 感谢重播,我如何使它被选中(行上的蓝色?
    • table->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows)
    • 你好,谁知道如何选择下一个/上一个行来跳过不可选择的行?所以它会模拟向下/向上箭头按下。当模型的行没有 Qt::ItemIsSelectable 或 Qt::ItemIsEnabled 标志时,上面的代码不起作用。
    【解决方案2】:
    /*
     * 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 );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多