Qt World Summit: Submit your Presentation

Select row and column from a table at the same time [SOLVED]

  • Hi,
    i am generating a grid. The grid is a qTableView item. I want when the window open the first row and column to be highlighted. I write these two lines for this purpose:

    but only the first column appears highlighted. As far as i understand when we do a selection it erases the previous selection. Is there a way to make it remember the selection of the row so i have the desired outcome?


  • QItemSelectionModel enables you to define the current selection very flexibly on a per-item basis:

    QItemSelectionModel* selection = myView->selectionModel();

    // Get model indexes to select

    // For all indexes
    selection->select(index, QItemSelectionModel::Select);

    The example above is rather simple. Using QItemSelection and QItemSelectionRange with the selection model you can solve your problem a lot more elegantly.

  • nice, thanks a lot

  • Code example:

    #include <QApplication>
    #include <QTableWidget>

    int main(int argc, char *argv[])
    int rows = 5, columns = 3;

    QApplication a(argc, argv);
    QTableWidget table(rows, columns);
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < columns; j++)
            table.setItem(i, j, new QTableWidgetItem(
                              QString("Item (%1, %2)")
                              .arg(i + 1).arg(j + 1)));
    QModelIndex zero = table.model()->index(0, 0);
    QModelIndex right = table.model()->index(0, columns - 1);
    QModelIndex bottom = table.model()->index(rows - 1, 0);
    QItemSelection selection(zero, right);
    selection.merge(QItemSelection(zero, bottom), QItemSelectionModel::Select);
    table.selectionModel()->select(selection, QItemSelectionModel::Select);
    return a.exec&#40;&#41;;


Log in to reply