Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting

Qt/C++ - Lesson 015. QTableWidget – How to create a table with checkboxes?

Qt, Qt Таблица, QTableWidget, QTableWidget example, QTableWidget пример

Using QTableWidget will be the first in a manner that will advise you to create tables with checkboxes on Qt. So let's look at this option and work with tables in Qt and certainly applicable checkboxes.

So, the lesson to be more close to reality, grabbed some code from lesson QDataWidgetMapper . Namely, take a class to work with the database, so they'd just do a table from the database. After that, make the shape of the main application window and output data from the table with the mapping checkboxes. Naturally, when the application database table is created and populated by several records, which we will display in the widget.

Project Structure for QTableWidget

I suggest to get acquainted with the project structure:

  • - profile;
  • mainwindow.h - header file of the main application window;
  • mainwindow.cpp - source of window;
  • main.cpp - the main source file from which the application starts;
  • mainwindow.ui - form of the main application window;
  • database.h - header file of helper class to be used for information that is placed in a database;
  • database.cpp - source of helper class file to be used for information that is placed in a database;


All you need to do with this file, it is set the QTableWidget in the form of the main window in the designer.


This file is declared to the database object with which we work, as well as a method for filling QTableWidget data.


#include <QMainWindow>
#include <QSqlQuery>

/* My includes */
#include <database.h>

namespace Ui {
class MainWindow;

class MainWindow : public QMainWindow

    explicit MainWindow(QWidget *parent = 0);

    Ui::MainWindow  *ui;
    DataBase        *db;

    void createUI(const QStringList &headers);

#endif // MAINWINDOW_H


This file is contained in all the purpose of the lesson, namely QTableWidget setting and filling his records from the database.

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)

    this->setWindowTitle("QTableWidget Example");
    /* The first step is to create an object for the database 
     * and initialize the database connection
     * */
    db = new DataBase();

    /* Fill the database records */
    for(int i = 1; i < 5; i++){
        /* Insert a record into the table, immediately set the state of the checkbox. 
         * If the device has an odd number, the status of the checkbox to true, otherwise false
         * */
        db->inserIntoDeviceTable(QVariantList() << QString::number(i & 1)
                                                << "Device " + QString::number(i)
                                                << "192.168.0." + QString::number(i)
                                                << "AA:AA:AA:AA:AA:A" + QString::number(i));

    this->createUI(QStringList() << trUtf8("id")
                                 << trUtf8("Нечетность")
                                 << trUtf8("Имя компьютера")
                                 << trUtf8("IP адрес")
                                 << trUtf8("MAC адрес")

    delete ui;

/* The method to configure the interface, 
 * the method will be carried out to fill QTableWidget records from the table
 * */
void MainWindow::createUI(const QStringList &headers)

    QSqlQuery query("SELECT "
                    DEVICE ".id, "
                    DEVICE "." DEVICE_CHECK_STATE ", "
                    DEVICE "." DEVICE_HOSTNAME ", "
                    DEVICE "." DEVICE_IP ", "
                    DEVICE "." DEVICE_MAC
                    " FROM " DEVICE);

    /* Perform filling QTableWidget records using a loop
     * */
    for(int i = 0;; i++){
        // Insert row
        /* Set the id column in the first taking it from the result of the SQL-query. 
         * This column will be hidden
         * */
        ui->tableWidget->setItem(i,0, new QTableWidgetItem(query.value(0).toString()));

        // Create an element, which will serve as a checkbox
        QTableWidgetItem *item = new QTableWidgetItem();
        /* Check on the status of odd if an odd device, 
         * exhibiting state of the checkbox in the Checked, Unchecked otherwise
         * */
        if(query.value(1).toInt() == 1){
        } else {
        // Set the checkbox in the second column
        ui->tableWidget->setItem(i,1, item);
        // Next, pick up all the data from a result set in other fields
        ui->tableWidget->setItem(i,2, new QTableWidgetItem(query.value(2).toString()));
        ui->tableWidget->setItem(i,3, new QTableWidgetItem(query.value(3).toString()));
        ui->tableWidget->setItem(i,4, new QTableWidgetItem(query.value(4).toString()));



This file is different from what has been taken from the lessons of QDataWidgetMapper that has been added to define a directive for the checkbox, respectively, this resulted in a change in the methods database.cpp file. Namely insertIntoDeviceTable and createDeviceTable .

#ifndef DATABASE_H
#define DATABASE_H

#include <QObject>
#include <QSql>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlDatabase>
#include <QFile>
#include <QDate>
#include <QDebug>

#define DATABASE_HOSTNAME   "ExampleDataBase"
#define DATABASE_NAME       "DataBase.db"

#define DEVICE                  "DeviceTable"
#define DEVICE_CHECK_STATE      "CheckState"
#define DEVICE_HOSTNAME         "Hostname"
#define DEVICE_IP               "IP"
#define DEVICE_MAC              "MAC"

class DataBase : public QObject
    explicit DataBase(QObject *parent = 0);

    void connectToDataBase();
    bool inserIntoDeviceTable(const QVariantList &data);

    QSqlDatabase    db;

    bool openDataBase();
    bool restoreDataBase();
    void closeDataBase();
    bool createDeviceTable();

#endif // DATABASE_H


#include "database.h"

DataBase::DataBase(QObject *parent) : QObject(parent)




void DataBase::connectToDataBase()
    if(!QFile("C:/example/" DATABASE_NAME).exists()){
    } else {

bool DataBase::restoreDataBase()
            return false;
        } else {
            return true;
    } else {
        qDebug() << "Failed to restore the database";
        return false;
    return false;

bool DataBase::openDataBase()
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("C:/example/" DATABASE_NAME);
        return true;
    } else {
        return false;

void DataBase::closeDataBase()

bool DataBase::createDeviceTable()
    QSqlQuery query;
    if(!query.exec( "CREATE TABLE " DEVICE " ("
                            "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                            DEVICE_CHECK_STATE " INTEGER       NOT NULL,"
                            DEVICE_HOSTNAME  " VARCHAR(255)    NOT NULL,"
                            DEVICE_IP        " VARCHAR(16)     NOT NULL,"
                            DEVICE_MAC       " VARCHAR(18)     NOT NULL"
                        " )"
        qDebug() << "DataBase: error of create " << DEVICE;
        qDebug() << query.lastError().text();
        return false;
    } else {
        return true;
    return false;

bool DataBase::inserIntoDeviceTable(const QVariantList &data)
    QSqlQuery query;
    query.prepare("INSERT INTO " DEVICE " ( " DEVICE_CHECK_STATE ", "
                                              DEVICE_HOSTNAME ", "
                                              DEVICE_IP ", "
                                              DEVICE_MAC " ) "
                  "VALUES (:CheckState, :Hostname, :IP, :MAC )");
    query.bindValue(":CheckState",  data[0].toInt());
    query.bindValue(":Hostname",    data[1].toString());
    query.bindValue(":IP",          data[2].toString());
    query.bindValue(":MAC",         data[3].toString());

        qDebug() << "error insert into " << DEVICE;
        qDebug() << query.lastError().text();
        return false;
    } else {
        return true;
    return false;


As a result, when you run the program will create an application, which will be a table with four entries, two of which are marked with checkboxes.

Application Example QTableWidget
Virtual hosting with 10 percent discount
Virtual hosting with 10 percent discount
EVILEG offers reliable hosting with a 10% discount for virtual hosting and 5% for VPS

Спасибо за статью, не подскажите  как можно использовать отмеченные чек боксом строчки. Мне их нужно скопировать их в другой QTableWidgetItem ?

Ответил на форуме .


В файле mainwindow.cpp строка 86: item->data(Qt::CheckStateRole); // без слов

ну да, затесался неудалённый кусок ерунды, надо будет отредактировать на досуге статью.


Only authorized users can post comments.
Please, Log in or Sign up
Last comments
March 19, 2019, 12:57 p.m.

Добрый день. А проверить работоспособность локально как-то можно не указывая реальнй сайт (еще в разработке)
March 16, 2019, 1:55 p.m.

Спасибо за статью. Давно итересует следующий вопрос: с помощью переменных QMAKE_TARGET_COMPANYQMAKE_TARGET_PRODUCTQMAKE_TARGET_DESCRIPTIONможно задать свойства компилируемой программы, о...
March 12, 2019, 10:19 a.m.
Jean Stefanovich

Большое спасибо за разъяснения!
March 12, 2019, 10:04 a.m.
Евгений Легоцкой

Hello, In fact, this functionality or is not implemented, or is not documented. I'm not sure. But I think, that it should be implemented in Text QML Type. Because of we can write text in...
March 12, 2019, 9:51 a.m.
Евгений Легоцкой

Да вы правы. На самом деле проще через QSqlQueryModel, сколько не пытался использовать эти дженерики типо QSqlTableModel и QSqlRelationalTableModel, то всегда упирался в какие-то их ограничени...
Now discuss on the forum
March 19, 2019, 1:43 p.m.

Очень интересная тема. У вас случайно нет статьи с полным циклом интреграции нескольких языков?Так сказать с нуля, что нужно, какие пакеты ставить, что куда писать. Тут вроде информации не ма...
March 17, 2019, 10:47 p.m.
Евгений Легоцкой

Добрый день. Вот, нашлось у меня немного времени. Делается это через шаблон проектирования наблюдатель.
March 15, 2019, 9:52 p.m.
Чарльз Грин

спасибо, попробую, отпишусь
March 15, 2019, 7:41 p.m.

Сори догадался)
March 12, 2019, 4:57 p.m.

Большооооое спасибо!!!!!Не передать как я вам благодарен, спасибо что всегда отзываетесь.Теперь я смогу продолжить работу в QT!!! (пробую писать бота (Я как вы могли догадаться немного не пр...
Join us in social networks

For registered users on the site there is a minimum amount of advertising