Qt5 Tutorial ModelView with QListView and QStringListModel - 2020
In this tutorial, we will learn about ModelView with QListView and QStringListModel.
In this example, we'll use Qt Gui application with QDialog:
Qt's MVC may not be the same as the conventional MVC.
If the view and the controller objects are combined, the result is the model/view architecture. This still separates the way that data is stored from the way that it is presented to the user, but provides a simpler framework based on the same principles. This separation makes it possible to display the same data in several different views, and to implement new types of views, without changing the underlying data structures. To allow flexible handling of user input, we introduce the concept of the delegate. The advantage of having a delegate in this framework is that it allows the way items of data are rendered and edited to be customized.However, it's worth investigating their approach of using "delegate" with their Model/View pattern.
We'll use Model-Based ListView rather than simple Item-Based List Widget:
When we update data using the three buttons, the Model(data) in ListView/ComboxBox View will also be updated.
Since we finished design, now is the time for coding.
Let's setup slots for the three buttons by "Go to slot..."->clicked().
void ModelViewDialog::on_pushButton_clicked() { // Add button clicked } void ModelViewDialog::on_pushButton_2_clicked() { // Insert button clicked } void ModelViewDialog::on_pushButton_3_clicked() { // Delete button clicked }
Then, we need to make our QStringListModel. Put the following line in the private section of modelviewdialog.h:
QStringListModel *model;
The QStringListModel class provides a model that supplies strings to views.
QStringListModel is an editable model that can be used for simple cases where you need to display a number of strings in a view widget, such as a QListView or a QComboBox.
The model provides all the standard functions of an editable model, representing the data in the string list as a model with one column and a number of rows equal to the number of items in the list.
Go to the dialog implementation file, modelviewdialog.cpp.
#include "modelviewdialog.h" #include "ui_modelviewdialog.h" ModelViewDialog::ModelViewDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ModelViewDialog) { ui->setupUi(this); // Create model model = new QStringListModel(this); // Make data QStringList List; List << "Clair de Lune" << "Reverie" << "Prelude"; // Populate our model model->setStringList(List); // Glue model and view together ui->listView->setModel(model); ui->comboBox->setModel(model); // Add additional feature so that // we can manually modify the data in ListView // It may be triggered by hitting any key or double-click etc. ui->listView-> setEditTriggers(QAbstractItemView::AnyKeyPressed | QAbstractItemView::DoubleClicked); }
What we've done:
- Created model.
- Populated our model.
- Glued model and view together.
- Add additional feature so that we can manually modify the data in ListView.
At this point, we have already included headers in modelviewdialog.h:
#include <QStringList> #include <QStringListModel> #include <QAbstractItemView>
To check we're on track, let's run the code:
Yes, it seems OK!
As a final step, let's work on the slots for our three buttons:
void ModelViewDialog::on_pushButton_clicked() { // Add button clicked // Adding at the end // Get the position int row = model->rowCount(); // Enable add one or more rows model->insertRows(row,1); // Get the row for Edit mode QModelIndex index = model->index(row); // Enable item selection and put it edit mode ui->listView->setCurrentIndex(index); ui->listView->edit(index); } void ModelViewDialog::on_pushButton_2_clicked() { // Insert button clicked // Get the position int row = ui->listView->currentIndex().row(); // Enable add one or more rows model->insertRows(row,1); // Get row for Edit mode QModelIndex index = model->index(row); // Enable item selection and put it edit mode ui->listView->setCurrentIndex(index); ui->listView->edit(index); } void ModelViewDialog::on_pushButton_3_clicked() { // Delete button clicked // For delete operation, // we're dealing with a Model not a View // Get the position model->removeRows(ui->listView->currentIndex().row(),1); }
Now, we're able to "add", "insert", and "delete". Whatever's done on the ListView will update the ComboBox as well.
Here are the final codes:
modelviewdialog.h:
#ifndef MODELVIEWDIALOG_H #define MODELVIEWDIALOG_H #include <QDialog> #include <QStringList> #include <QStringListModel> #include <QAbstractItemView> namespace Ui { class ModelViewDialog; } class ModelViewDialog : public QDialog { Q_OBJECT public: explicit ModelViewDialog(QWidget *parent = 0); ~ModelViewDialog(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); void on_pushButton_3_clicked(); private: Ui::ModelViewDialog *ui; QStringListModel *model; }; #endif // MODELVIEWDIALOG_H
modelviewdialog.cpp:
#include "modelviewdialog.h" #include "ui_modelviewdialog.h" ModelViewDialog::ModelViewDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ModelViewDialog) { ui->setupUi(this); // Create model model = new QStringListModel(this); // Make data QStringList List; List << "Clair de Lune" << "Reverie" << "Prelude"; // Populate our model model->setStringList(List); // Glue model and view together ui->listView->setModel(model); ui->comboBox->setModel(model); // Add additional feature so that // we can manually modify the data in ListView // It may be triggered by hitting any key or double-click etc. ui->listView-> setEditTriggers(QAbstractItemView::AnyKeyPressed | QAbstractItemView::DoubleClicked); } ModelViewDialog::~ModelViewDialog() { delete ui; } void ModelViewDialog::on_pushButton_clicked() { // Add button clicked // Adding at the end // Get the position int row = model->rowCount(); // Enable add one or more rows model->insertRows(row,1); // Get the row for Edit mode QModelIndex index = model->index(row); // Enable item selection and put it edit mode ui->listView->setCurrentIndex(index); ui->listView->edit(index); } void ModelViewDialog::on_pushButton_2_clicked() { // Insert button clicked // Get the position int row = ui->listView->currentIndex().row(); // Enable add one or more rows model->insertRows(row,1); // Get row for Edit mode QModelIndex index = model->index(row); // Enable item selection and put it edit mode ui->listView->setCurrentIndex(index); ui->listView->edit(index); } void ModelViewDialog::on_pushButton_3_clicked() { // Delete button clicked // For delete operation, // we're dealing with a Model not a View // Get the position model->removeRows(ui->listView->currentIndex().row(),1); }
Qt 5 Tutorial
- Hello World
- Signals and Slots
- Q_OBJECT Macro
- MainWindow and Action
- MainWindow and ImageViewer using Designer A
- MainWindow and ImageViewer using Designer B
- Layouts
- Layouts without Designer
- Grid Layouts
- Splitter
- QDir
- QFile (Basic)
- Resource Files (.qrc)
- QComboBox
- QListWidget
- QTreeWidget
- QAction and Icon Resources
- QStatusBar
- QMessageBox
- QTimer
- QList
- QListIterator
- QMutableListIterator
- QLinkedList
- QMap
- QHash
- QStringList
- QTextStream
- QMimeType and QMimeDatabase
- QFile (Serialization I)
- QFile (Serialization II - Class)
- Tool Tips in HTML Style and with Resource Images
- QPainter
- QBrush and QRect
- QPainterPath and QPolygon
- QPen and Cap Style
- QBrush and QGradient
- QPainter and Transformations
- QGraphicsView and QGraphicsScene
- Customizing Items by inheriting QGraphicsItem
- QGraphicsView Animation
- FFmpeg Converter using QProcess
- QProgress Dialog - Modal and Modeless
- QVariant and QMetaType
- QtXML - Writing to a file
- QtXML - QtXML DOM Reading
- QThreads - Introduction
- QThreads - Creating Threads
- Creating QThreads using QtConcurrent
- QThreads - Priority
- QThreads - QMutex
- QThreads - GuiThread
- QtConcurrent QProgressDialog with QFutureWatcher
- QSemaphores - Producer and Consumer
- QThreads - wait()
- MVC - ModelView with QListView and QStringListModel
- MVC - ModelView with QTreeView and QDirModel
- MVC - ModelView with QTreeView and QFileSystemModel
- MVC - ModelView with QTableView and QItemDelegate
- QHttp - Downloading Files
- QNetworkAccessManager and QNetworkRequest - Downloading Files
- Qt's Network Download Example - Reconstructed
- QNetworkAccessManager - Downloading Files with UI and QProgressDialog
- QUdpSocket
- QTcpSocket
- QTcpSocket with Signals and Slots
- QTcpServer - Client and Server
- QTcpServer - Loopback Dialog
- QTcpServer - Client and Server using MultiThreading
- QTcpServer - Client and Server using QThreadPool
- Asynchronous QTcpServer - Client and Server using QThreadPool
- Qt Quick2 QML Animation - A
- Qt Quick2 QML Animation - B
- Short note on Ubuntu Install
- OpenGL with QT5
- Qt5 Webkit : Web Browser with QtCreator using QWebView Part A
- Qt5 Webkit : Web Browser with QtCreator using QWebView Part B
- Video Player with HTML5 QWebView and FFmpeg Converter
- Qt5 Add-in and Visual Studio 2012
- Qt5.3 Installation on Ubuntu 14.04
- Qt5.5 Installation on Ubuntu 14.04
- Short note on deploying to Windows
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization