Table of Content
English Български
How to Use QTableWidget
QTableWidget Overview
Using QTableWidget [qt-project.org] developers can embed tables inside Qt applications. QTableWidget inherits QTableView [qt-project.org]. Items in a QTableWidget instance are provided by class QTableWidgetItem [qt-project.org].
Basic Usage
Set number of rows and columns
- m_pTableWidget->setRowCount(10);
- m_pTableWidget->setColumnCount(3);
Insert labels into the horizontal header
- m_TableHeader<<"#"<<"Name"<<"Text";
- m_pTableWidget->setHorizontalHeaderLabels(m_TableHeader);
Insert data
The simplest way to insert text into a cell:
Hide vertical header aka the line counter
- m_pTableWidget->verticalHeader()->setVisible(false);
Hide grid
- m_pTableWidget->setShowGrid(false);
Set background of the selected items
- m_pTableWidget->setStyleSheet("QTableView {selection-background-color: red;}");
Disable editing
Selection mode and behavior
The behavior of the table for selecting rows and cells can be customized using methods setSelectionBehavior [qt-project.org] and setSelectionMode [qt-project.org]. The following example allows only single selection of a row:
Handling signals
QTableWidget provides appropriate signals for each event such as change of selection, click, double click, etc. [doc.qt.nokia.com] Example of handling double click of a cell:
- connect( m_pTableWidget, SIGNAL( cellDoubleClicked (int, int) ), this, SLOT( cellSelected( int, int ) ) );
Example
The following code snippet uses QTableWidget and all described cases above. It has been tested on Symbian^3 device.
- mainwindow.h
- #include <QTableWidget>
- private slots:
- void cellSelected(int nRow, int nCol);
- private:
- QStringList m_TableHeader;
- mainwindow.cpp
- #include "mainwindow.h"
- #include <QApplication>
- #include <QDesktopWidget>
- #include <QtCore/QCoreApplication>
- #include <QHeaderView>
- #include <QMessageBox>
- m_pTableWidget(NULL)
- {
- m_pTableWidget->setRowCount(10);
- m_pTableWidget->setColumnCount(3);
- m_TableHeader<<"#"<<"Name"<<"Text";
- m_pTableWidget->setHorizontalHeaderLabels(m_TableHeader);
- m_pTableWidget->verticalHeader()->setVisible(false);
- m_pTableWidget->setShowGrid(false);
- m_pTableWidget->setStyleSheet("QTableView {selection-background-color: red;}");
- //insert data
- connect( m_pTableWidget, SIGNAL( cellDoubleClicked (int, int) ),
- this, SLOT( cellSelected( int, int ) ) );
- }
- MainWindow::~MainWindow()
- {
- }
- void MainWindow::cellSelected(int nRow, int nCol)
- {
- " was double clicked.");
- }
See Also
How to use QTableWidget in Qt [developer.nokia.com]
Customizing QTableView [doc.qt.nokia.com]

