Presenting Data in a Table View Using Qt

Posted By : Satish Joshi | 30-Sep-2019

Introduction :

 

In Qt, there is a QTableView named class which implements a table view and displays item from a model and is part of Qt's model/view framework. This class is used to provide standard tables that are already previously provided by QTable class, but using it in a more flexible & easy approach provided by Qt's model/view architecture.

At last, QTableView implements the interfaces provided by the QAbstractItemView class to allow it to display data provided by models that are derived from the QAbstractItemModel class.

 

Properties :

 

  1. We can Navigate the cells in the table by clicking on a cell with the help of the mouse, or by using arrow keys.
  2. We can set our grid properties like showGrid, gridStyle for the table view.
  3. We can also enable sorting & word-wrap like properties in the table view. As you can refer to this link for additional info: https://doc.qt.io/qt-5/qtableview.html

 

Implementation :

 

First of all, the table has a vertical & a horizontal header that is available through verticalHeader() & horizontalHeader() function or you can set it with the help of QStandardItemModel. So let's start creating a table view structure as you can start selecting the Table View under your's project Design View where you can simply Drag & Drop the items for your project which you will create by inheriting QMainWindow.

 

Example :

 

//First Declare these terms in your header file like this :

    QStandardItemModel *model;    
    QStringList horizontalHeader;
    QStringList verticalHeader;

    //Then in your .cpp file use them like this :

    //Here we are setting your columns

    horizontalHeader.append("COLUMN 1");
    horizontalHeader.append("COLUMN 2");

    // Here we are creating our model

    model = new QStandardItemModel();

    model->setHorizontalHeaderLabels(horizontalHeader);
    model->setVerticalHeaderLabels(verticalHeader);

    ui->tableView->setModel(model); // This is necessary to display the data on table view
    ui->tableView->verticalHeader()->setVisible(false);
    ui->tableView->verticalHeader()->setDefaultSectionSize(10);
    ui->tableView->setShowGrid(false);

    // Here you can set your data in table view

    QStandardItem *col1 = new QStandardItem("Text 1");
    QStandardItem *col2 = new QStandardItem("Text 2");

    model->appendRow( QList<QStandardItem*>() << col1 << col2);

 

 

Here, In this example, we showed you how you will use your table view very effectively. For more info, you can refer ton Qt's official Doc.

 

Thank you for Reading.

About Author

Author Image
Satish Joshi

Satish has experience on web development believes in hard work and dedication. He is friendly and an honest person.

Request for Proposal

Name is required

Comment is required

Sending message..