Hareen Laks
Hareen Laks

Reputation: 1505

How to select top item of QTableView

I created QTableView as below and want to select the top item as default selection.

proxyModel = new QSortFilterProxyModel(this);
    proxyModel->setSourceModel(d->model);

    d->ui->projects->setModel(proxyModel);
    d->ui->projects->setSortingEnabled(true);
    proxyModel->setFilterCaseSensitivity( Qt::CaseInsensitive );
    proxyModel->setFilterKeyColumn(-1);

    connect(d->ui->projects->model(),SIGNAL(dataChanged(QModelIndex,QModelIndex)),d,SLOT(selectTopOne()));
connect ( d->ui->search_phrase, SIGNAL( textChanged(QString)),
              proxyModel, SLOT( setFilterWildcard(QString)) );

Note that d->ui->projects represents my QTableView. and d->ui->projects is text edit use to grab search string.

I tried to select top item of my table view by calling Slot selectTopOne through the dataChanged signala. But it is not calling for Slot.

And I tried to select row with Qmodelindex (0,0). But it not worked too.

EDIT:

This is How my QTableview appears now.

enter image description here

This is What I need to do. I need to select first row automatically.

enter image description here

According to the Text Edit on top items of QTableview filtered. I want to select top item at that time too.

enter image description here

Upvotes: 0

Views: 2656

Answers (2)

Jar Yit
Jar Yit

Reputation: 985

I hope this answer will help you.

ui.tableView->selectRow(0);
ui.tableView->setFocus();

Upvotes: 1

Shtol Krakov
Shtol Krakov

Reputation: 1280

Why do you use dataChange() signal to set default selection? Am I right that you want select top item by default on start the program? You can just use selection model, for example:

 d->ui->projects->selectionModel()->select(d->ui->projects->model()->index(0,0), QItemSelectionModel::Select);

AFTER YOUR EDIT:

OK, I've got it. The decision (for example) is inheritance from QSortFilterProxyModel class. There you can use some SLOT that will be use setFilterRexExp() (or smth else probably) when you'll change text in QLineEdit. After that sending some SIGNAL from this SLOT that you can catch from your main class and call method that I wrote upper, which select first item. Or, if you don't use model index's data do:

d->ui->projects->setCurrentIndex(d->ui->projects->model()->index(0,0));

Upvotes: 0

Related Questions