How to select several cells from a QTableWidget?



  • Hi,

    I need to select an specific range of cell items in a QTableWidget object directly from my code. My input is a list with the cell coordinates (int column. int row) that makes part of the selection. Example of input: [0, 1] [0, 2] [0, 3]

    Any hint?

    PS: I found this piece of code and I wonder if there's a way to create my own QItemSelection object, assigning the items I want to select. Is it possible?

    QItemSelection selectedItems = tableView->selectionModel()->selection();
    tableView->selectionModel()->clearSelection();
    tableView->selectionModel()->select(selectedItems, QItemSelectionModel::Select);
    
    


  • Have You read the QItemSelectionModel reference page?
    It seems to be what You need.
    http://doc.qt.io/qt-5/qitemselectionmodel.html



  • void selectIndexes(const QModelIndexList& indexes){
    tableWidget->selectionModel()->clearSelection();
    for(auto& singleIdx : indexes)
    tableWidget->selectionModel(singleIdx , QItemSelectionModel::Select);
    }
    


  • I know I 'm in the right direction, but there is a point where I got stuck: if I can instance items of the QModelIndex class using the coords I already have, I can solve my problem easily as in the example you suggest... but how?

    Checking the QModelIndex method s, there is no set actions of any kind. How can I define a QModelIndex with the cell position (column, row), i.e. (0,1)? I have been reading the view/model documentation but I must confess I am lost about this specific topic :(



  • @xtingray said in How to select several cells from a QTableWidget?:

    I can instance items of the QModelIndex class using the coords I already have, I can solve my problem easily as in the example you suggest... but how?

    easy!
    tableWidget->model()->index(row,column);



  • Don't forget to set :

    void setSelectionMode(QAbstractItemView::SelectionMode mode)
    setSelectionBehavior(QAbstractItemView::SelectRows);


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.