Irene
Irene

Reputation: 25

How to display a vector of elements on a list view?

I have two functions getProjects() and getEmployees(), in a class called manage from manage.h, that basically return a vector with all the projects/employees I've added until now.

How can I display it in my Qt application interface?

I've created two buttons (in a stackedWidget), one to get all the projects when clicked and the other one for the employees, and I've also used a QListView that should show all my data when I click one of the two buttons, but how do I tell the QListView to display my vector's elements?

I think the solution would look like something like this:

void MainWindow::on_showAllProjects_pushButton_clicked()
{
    ui->listView->something(manage.getProjects());
}

Upvotes: 0

Views: 200

Answers (1)

user17726418
user17726418

Reputation: 2365

You first need a QStringList to put the elements of your vector into, then a QStringListModel, which you need to set its stringlist to your stringlist, then set this QStringListModel as your listview model, and that does what you need.

Here's an example:

QStringListModel *model = new QStringListModel(this);

QStringList List;
List << "Project1" << "Project2" << "Project3";

model->setStringList(List);
ui->listView->setModel(model);

If you don't have to use the model based list, you can use QListWidget instead, it provides a method addItem(), which is very straightforward compared to QListView.

For more: Qt5 Tutorial ModelView with QListView and QStringListModel.

Upvotes: 0

Related Questions