Home > Enterprise >  QTableView, select row and shift click
QTableView, select row and shift click

Time:07-27

I have a QTableview in an app, the selectionMode is set to QAbstractItemView::ExtendedSelection.

I have a button from which I select a specific row of the table view, using below call.

myTableView->selectRow(rowNumber);

The problem is, that if I have a row i selected. then press my button, row j is selected. Then when I then shift click another row k. The selection in the tableview will be from i->k, not j->k.

This question is essentially a duplicate of this question. But none of the discussed solutions work. The author in a comment on the accepted answer even says the accepted answer does not work.

I have tried calling the setCurrentIndex method before and after the selectRow method. But it made no change.

CodePudding user response:

Looks like you are facing similar issue to what you linked: you don't set current index together with selection change. Small example to illustrate:

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    
    QStringListModel model( { "First", "Second", "Third", "Fouth" });
    auto p_view = new QTableView;
    p_view->setModel(&model);

    auto p_btn = new QPushButton("Select second row");
    QObject::connect(p_btn, &QAbstractButton::pressed, [p_view]() {
        p_view->selectRow(1);
        p_view->setCurrentIndex(p_view->model()->index(1,0));
    });

    auto p_layout = new QHBoxLayout;
    p_layout->addWidget(p_view);
    p_layout->addWidget(p_btn);

    QWidget main;
    main.setLayout(p_layout);
    main.show();
    
    return app.exec();
}

Here row p_view->setCurrentIndex(p_view->model()->index(1,0)); will do the difference.

  • Related