Select behavior in Qtableview when remove item.

  • Hi guys,

    when i select an item in QTableView, for example, index(1, 0).
    after that, i removed the item selected, who's row is 1. then, the next item will be selected automaticly.
    i wanna disable this featue.
    so, is there any way to do this?

  • Hi jmelbye,

    thanks for ur reply.
    but i don't think your solution can work since the next item will be selected a little later after one item is removed.
    so , anyway, operation clearSelection will be executed before the next item is selected.
    actually, what i want is to disable the feature which will switch selection after current selection is removed.
    do u have any good idea?

  • This works:
    class MainWindow: public QMainWindow {
    MainWindow(QWidget *p = 0): QMainWindow(p) {
    QWidget *central = new QWidget(this);
    view = new QTableView(this);
    QPushButton *button = new QPushButton("Delete", this);
    connect(button, SIGNAL(clicked()), SLOT(doit()));

        model = new QStandardItemModel(3,3,this);
        for (int r = 0; r < 3; ++r)
            for (int c = 0; c < 3; ++c)
                model->setItem(r, c, new QStandardItem(QString("%1,%2").arg(r).arg(c)));
        QVBoxLayout *layout = new QVBoxLayout(central);

    public slots:
    void doit() {
    QModelIndexList indexes = view->selectionModel()->selectedRows();
    qDebug() << "Before" << indexes;
    if (indexes.count() > 0) {
    const QModelIndex index = view->selectionModel()->selectedRows().at(0);
    qDebug() << "After" << view->selectionModel()->selectedRows();


    QTableView *view;
    QStandardItemModel *model;
    After deleting a row there is no selection (visible or not)

    Why don't you show us what you are actually doing and perhaps we can help.

  • Only a quick word, but don't forget the "beginRemoveRows" and "endRemoveRows" in the doit() function!! That gives the view information about what happens in side the model and keeps your view/model concept in sync!

  • Those functions are neither needed nor accessible in the doit() function: the example code is not implementing a model, just manipulating one. These protected functions are called in the model code before it adjusts row/column counts and cause the emission of the corresponding signals from the model.

  • Hi all,
    thanks for your help.
    but i don't think it works well in my code.
    actually, the problem in my project is that: when i remove an item from model, even i cleared selection, table will auto make another item be selected after an item is removed.
    it seems that it's a widget feature. i mean, when an item is removed, selected index will be updated automaticly.
    so, what i wanna is that, is there any way to disable the feature?

Log in to reply

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