Evgenii Legotckoi
Evgenii LegotckoiSept. 4, 2015, 11:30 a.m.

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

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:

  • QTableWidgetExample.pro - 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;

mainwindow.ui

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

mainwindow.h

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

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QSqlQuery>

/* My includes */
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QSqlQuery>

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

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow  *ui;
    DataBase        *db;

private:
    void createUI(const QStringList &headers);
};

#endif // MAINWINDOW_H

mainwindow.cpp

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) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

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

    /* 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 адрес")
               );
}

MainWindow::~MainWindow()
{
    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)
{
    ui->tableWidget->setColumnCount(5); 
    ui->tableWidget->setShowGrid(true); 
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setHorizontalHeaderLabels(headers);
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->hideColumn(0);

    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; query.next(); i++){
        // Insert row
        ui->tableWidget->insertRow(i);
        /* 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();
        item->data(Qt::CheckStateRole);
        /* 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){
            item->setCheckState(Qt::Checked);
        } else {
            item->setCheckState(Qt::Unchecked);
        }
        // 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()));
    }

    ui->tableWidget->resizeColumnsToContents();
}

database.h

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
{
    Q_OBJECT
public:
    explicit DataBase(QObject *parent = 0);
    ~DataBase();

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

private:
    QSqlDatabase    db;

private:
    bool openDataBase();
    bool restoreDataBase();
    void closeDataBase();
    bool createDeviceTable();
};

#endif // DATABASE_H

database.cpp

#include "database.h"

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

}

DataBase::~DataBase()
{

}

void DataBase::connectToDataBase()
{
    if(!QFile("C:/example/" DATABASE_NAME).exists()){
        this->restoreDataBase();
    } else {
        this->openDataBase();
    }
}

bool DataBase::restoreDataBase()
{
    if(this->openDataBase()){
        if(!this->createDeviceTable()){
            return false;
        } else {
            return true;
        }
    } else {
        qDebug() << "Failed to restore the database";
        return false;
    }
    return false;
}

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

void DataBase::closeDataBase()
{
    db.close();
}

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());

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

Result

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.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Terabaytus
  • June 13, 2017, 4:39 a.m.

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

Evgenii Legotckoi
  • June 15, 2017, 1:33 a.m.

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

ЮВ
  • Jan. 12, 2019, 11:51 a.m.

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

Evgenii Legotckoi
  • Jan. 14, 2019, 3:28 a.m.

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

Ruslan Polupan
  • April 5, 2019, 7:50 a.m.

Доброго времени суток.
Возник вопрос по статье.
Как организовать сортировку по столбцу с CheckBox.
Т.е. чтобы отмеченные строки отображались в верхней части TableWidget.
Дополнительный скрытый столбец делать или есть еще варианты?

Evgenii Legotckoi
  • April 5, 2019, 9:10 a.m.
  • (edited)

Добрый день. Добавьте ORDER BY в заппрос SELECT по столбцу с чекбоксами.

Ruslan Polupan
  • April 6, 2019, 3:48 p.m.

Дело в том что чтолбец с чекбоксами никак не связан с базой. Он только для выбора объектов.

Evgenii Legotckoi
  • April 8, 2019, 3:27 a.m.

На ум приходит несколько вариантов:

  • добавлять все взятые из БД записи в вектор структур данных, в которых будет дополнительное поле под чекбокс и выполнять сортировку этого вектора по полю чекбокса.
  • Всё тоже самое, только уже переписать на QTableView и сделать полноценную модель данных.

Можно конечно, как-то написать костыли на изменение позиций строчек при наличии выделенного чекбокса, но это будут костыли. Лучше уж перейти на полноценную модель данных в данном случае и QTableView

ВК
  • Sept. 9, 2020, 6:35 a.m.
  • (edited)

Попробовал запустить код, описанный в данной статье, но получаю следующее:

Подскажите в чем может быть проблема ?
Вывод окна - пустой:

Evgenii Legotckoi
  • Sept. 9, 2020, 6:42 a.m.

Пока добавляли у себя код, что-то пробовали проверяли, могло дойти до ситуации, когда у вас получилась создана таблица, с количеством колонок, не совпадающим с количеством колонок в финальной версии. В общем в INSERT запросе у вас больше или меньше аргументов, чем колонок в таблице DEVICE по факту.

Да, у меня тоже такая мысль возникла, но я просто скопипастил этот код из статьи, ничего в нем не меняя.

ВК
  • Sept. 9, 2020, 6:56 a.m.
  • (edited)

Кажется я понял в чем ошибка - я вручную создал таблицу Device в базе данных DataBase.db через DB Browser for SQLite в корне проекта с соответствующими типами данных и по какой-то причине insert не выполнялся, как только БД удалил, пример заработал.

ВК
  • Sept. 29, 2020, 8:08 a.m.

Кто-нибудь знает, как сделать так, чтобы в QTableWidget состоящей из чекбоксов в строке таблицы можно было выбрать только один checkbox ?

СБ
  • Dec. 26, 2020, 6:12 a.m.
  • (edited)

ошибки куда-то пропали, но база данных не заполняется

Comments

Only authorized users can post comments.
Please, Log in or Sign up
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 19, 2024, 7:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 4:57 p.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 12:18 p.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 2:48 p.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks