Qt QListView Tutorial

Qt QListView Tutorial

In my last article, I am write about toturial how to use QTableView. In this tutorial, I am try to write about Qt QListView Tutorial. The QListView class provides a list or icon view onto a model. That is like with QTableView. QListView support only one column (if you get a method how to create multiple column with QListView, maybe you can let me know 🙂 ). So, if you want to create mutliple column, you can use QTreeView or QTableView than QListView.

Below is a basic sample code how to use QListView (Qt QListView Tutorial). This code create a QListView, fill QListView with data, and show QListView program. From this Qt QListView Tutorial, you can extend to your program to more complex. Create a file, save with “listviewexample.cpp“, copy this text :

#include "listviewexample.h"

ListViewExample::ListViewExample( QWidget *parent)
    : QWidget( parent )
{
    /*set number of row and column, listview only support 1 column */
    nrow = 4;
    ncol = 1;

    /*create QListView */
    m_listView = new QListView(this);
    QStandardItemModel *model = new QStandardItemModel( nrow, 1, this );

    //fill model value
    for( int r=0; r<nrow; r++ )
    {
            QString sstr = "[ " + QString::number(r) + " ]";
            QStandardItem *item = new QStandardItem(QString("Idx ") + sstr);
            model->setItem(r, 0, item);
    }

    //set model
    m_listView->setModel(model);
}

int main( int argc, char **argv )
{
        QApplication a( argc, argv );

        ListViewExample lve;
        lve.show();

        return a.exec();
}

We can fill QListView item with QStandardItemModel class. This is header file for this Qt QListView Tutorial. Saving this text to “listviewexample.h” :

#ifndef LISTVIEWEXAMPLE_H
#define LISTVIEWEXAMPLE_H

#include <QListView>
#include <QStandardItemModel>
#include <QApplication>

class ListViewExample : public QWidget
{
	Q_OBJECT

public:
        ListViewExample( QWidget *parent=0);

private slots:

private:
        int nrow, ncol;
        QListView *m_listView;
};

#endif

Create a “listview.pro” file for this Qt QListView Tutorial and fill with this text :

TEMPLATE = app
INCLUDEPATH += .

# Input
HEADERS += listviewexample.h
SOURCES += listviewexample.cpp

Compile this Qt QListView Tutorial with command “qmake” and “make“. This is output from this Qt QListView Tutorial :

Qt QListView Tutorial
Qt_QListView_Tutorial

This is a basic tutorial how to use QListView (Qt QListView Tutorial), please let me know if you have a question. You can get the complete code Qt QListView Tutorial at here.

Source :
http://www.digitalfanatics.org/projects/qt_tutorial/chapter13.html

 

Add a Comment

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.