PDA

View Full Version : Highlight/activate first item in a QListView from code.



anr78
7th August 2011, 23:28
I'm using QListView and QFileSystemModel to display contents of some folders. When I use my keyboard or post QKeyEvents I can highlight items and move around like I want, but how can I do the same operations from code?

I want the first item in the rootIndex to be highlighted by default (like it is if I send Key_Home to the list), and to be able to move up and down in the list with function calls. I suspect maybe I can use setCurrentIndex to do the latter, if I find out how to do the first.

Dong Back Kim
8th August 2011, 01:47
I'm using QListView and QFileSystemModel to display contents of some folders. When I use my keyboard or post QKeyEvents I can highlight items and move around like I want, but how can I do the same operations from code?

I want the first item in the rootIndex to be highlighted by default (like it is if I send Key_Home to the list), and to be able to move up and down in the list with function calls. I suspect maybe I can use setCurrentIndex to do the latter, if I find out how to do the first.



QModelIndex index = model->createIndex( row, column );
if ( index.isValid() )
model->selectionModel()->select( index, QItemSelectionModel::Select );

anr78
8th August 2011, 09:34
Thanks. Trying to get this into my code now, with a couple of issues. model->createIndex is protected, so I'm trying to find another way to create the index. And I think model->selectionModel... should be list->selectionModel...

anr78
9th August 2011, 21:22
Been fiddling a bit more with this, and there seems to be something about this Model/View I don't understand. Below is the mainwindow.cpp from a small testproject I have made. The aim is to display folders from the model in my QListView, and higlight the second row. When the first timer goes off, LightItUp() does just that. When the second timer goes off, LightItUp2() opens the folder I want, but does not highlight any items. Am I not changing folders/indexes the way I'm supposed to?



#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QEvent>
#include <QKeyEvent>
#include <QDebug>
#include <QTimer>

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

model = new QFileSystemModel;
model->setRootPath("/Users/anders/Downloads");

list = new QListView;
list->setModel(model);
list->show();

QTimer::singleShot(3000, this, SLOT(LightItUp()));

}

void MainWindow::LightItUp()
{
qDebug("LightItUp");
list->setRootIndex(model->index(model->rootPath()));
list->setCurrentIndex(model->index(1, 0, list->rootIndex()));

QTimer::singleShot(3000, this, SLOT(LightItUp2()));
}

void MainWindow::LightItUp2()
{
qDebug("LightItUp2");
list->setRootIndex(model->index("/Users/anders/Downloads/Browser"));
list->setCurrentIndex(model->index(1, 0, list->rootIndex()));
}


MainWindow::~MainWindow()
{
delete ui;
}