Ruslan Polupan
Ruslan PolupanApril 11, 2019, 6:01 a.m.

QCheckBox as QTableView delegate

Good day.
There was a need to use a delegate to display QCheckBox in the table (to select objects from the list for subsequent work with them).
In order to deal with the delegates, I created a small project.
At the output we get the following:


Project structure:

checkboxdelegate.h

#ifndef CHECKBOXDELEGATE_H
#define CHECKBOXDELEGATE_H
#include <QStyledItemDelegate>


class CheckBoxDelegate : public QStyledItemDelegate
{
    Q_OBJECT

public:
    CheckBoxDelegate(QObject *parent = nullptr);

    // QAbstractItemDelegate interface
public:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    void setEditorData(QWidget *editor, const QModelIndex &index) const;
    void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
};

#endif // CHECKBOXDELEGATE_H

checkboxdelegate.cpp

#include "checkboxdelegate.h"
#include <QCheckBox>
#include <QApplication>

CheckBoxDelegate::CheckBoxDelegate(QObject *parent)
    :QStyledItemDelegate (parent)
{

}

QWidget *CheckBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option)
    Q_UNUSED(index)

    //Cоздаем checkbox editor
    QCheckBox *editor = new QCheckBox(parent);
    return editor;
}

void CheckBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    //Установливаем выбрано/не выбрано
    QCheckBox *cb = qobject_cast<QCheckBox *>(editor);
    cb->setChecked(index.data().toBool());
}

void CheckBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    //Записываем данные в модель
    QCheckBox *cb = static_cast<QCheckBox *>(editor);
    int value = (cb->checkState()==Qt::Checked)? 1 : 0;
    model->setData(index, value, Qt::EditRole);
}

void CheckBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(index);
    QStyleOptionButton checkboxstyle;
    QRect checkbox_rect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkboxstyle);

    //Центрирование
    checkboxstyle.rect = option.rect;
    checkboxstyle.rect.setLeft(option.rect.x() +
                               option.rect.width()/2 - checkbox_rect.width()/2);

    editor->setGeometry(checkboxstyle.rect);
}


void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    //Получаем данные
    bool data = index.model()->data(index, Qt::DisplayRole).toBool();

    //Создаем стиль CheckBox
    QStyleOptionButton checkboxstyle;
    QRect checkbox_rect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkboxstyle);

    //Центрирование
    checkboxstyle.rect = option.rect;
    checkboxstyle.rect.setLeft(option.rect.x() +
                               option.rect.width()/2 - checkbox_rect.width()/2);
    //Выбрано или не выбрано
    if(data)
        checkboxstyle.state = QStyle::State_On|QStyle::State_Enabled;
    else
        checkboxstyle.state = QStyle::State_Off|QStyle::State_Enabled;

    //Готово! Отображаем!
    QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkboxstyle, painter);
}

main.cpp

#include "checkboxdelegate.h"
#include <QApplication>
#include <QStandardItemModel>
#include <QHeaderView>
#include <QTableView>

#define MODEL_ROWS 4            //Количество строк модели
#define MODEL_COLUMN 2          //Количество столбцов модели
#define DELEGATE_COLUMN 0       //Столбец с делегатом

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

    //Создаем модель и представление
    QStandardItemModel *model = new QStandardItemModel(MODEL_ROWS, MODEL_COLUMN);
    QTableView *tableView = new QTableView();
    CheckBoxDelegate *delegate = new CheckBoxDelegate();

    //Заолняем модель данными
    for (int row =0; row < MODEL_ROWS; ++row) {
        for (int column = 0; column < MODEL_COLUMN; ++column) {
            QModelIndex index = model->index(row, column, QModelIndex());
            if(column == 0)
                model->setData(index, QVariant(0));
            else
                model->setData(index, QVariant((row + 1) * (column + 1)));
        }

    }
    //Устанавливаем модель в представление
    tableView->setModel(model);
    //Устанавливаем делегат в столбец
    tableView->setItemDelegateForColumn(DELEGATE_COLUMN, delegate);
    //Внешний вид предтавления
    tableView->resizeColumnsToContents();
    tableView->verticalHeader()->hide();
    tableView->horizontalHeader()->setStretchLastSection(true);

    tableView->setWindowTitle("Check Box Delegate");
    tableView->show();

    return a.exec();
}

Project file:

CheckBoxDelegate_PG92889.7z CheckBoxDelegate_PG92889.7z

The only problem is that you have to double-click the QCheckBox to select it. It turns out that the cell is allocated at first. and only then the focus already falls on the widget.

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!

D
  • Aug. 11, 2019, 7:50 p.m.

Пример лучше скину после отпуска.

Ruslan Polupan
  • Aug. 12, 2019, 2:44 a.m.

Было бы интересно.

Evgenii Legotckoi
  • Aug. 12, 2019, 4:20 a.m.

Если это будет достаточно самостоятельный код, то вы бы тогда могли написать небольшую статью на эту тематику в раздел Qt.

D
  • Aug. 17, 2019, 9:04 a.m.
  • (edited)

github ChekableTView

Правой групповая смена значения при перетаскивании левой как обычно.

m
  • Jan. 27, 2020, 9:53 a.m.

Единственная проблема состоит в том, что для выделения QCheckBox приходится дважны нажимать мышь. Получается что сначала выделяется ячейка. а только потом фокус уже попадает на виджет.

Ну это как бы не проблема. Это отсутствие решения.

ПБ
  • Feb. 12, 2020, 2:42 a.m.

Как изменить цвет фона внутри checkbox (по возможности убрать рамку вокруг)?
Пробовал с цветом так:

QWidget *CheckBoxDelegate::createEditor(QWidget *parent,
                                        const QStyleOptionViewItem &,
                                        const QModelIndex &) const
{
    auto checkBox = new QCheckBox(parent);
    checkBox->setStyleSheet("QCheckBox::indicator {background-color: blue;}");

    return checkBox;
}
Ruslan Polupan
  • Feb. 12, 2020, 2:54 a.m.
  • (edited)

Я сейчас просто меняю изображения на CheckBox

    ui->checkBoxIsActive->setStyleSheet(
                      "QCheckBox::indicator:unchecked {image: url(:/Images/check_box_unchek.png);}"
                      "QCheckBox::indicator:checked {image: url(:/Images/check_box.png);}");

Это не то, мне нужно именно делегат отредактировать (без изображения)

D
  • Sept. 20, 2020, 3:34 p.m.
  • (edited)
bool Node::setData(const QModelIndex& index, const QVariant& value, int role)
{
    switch (index.column()) {
    case 0:
        switch (role) {
        case Qt::CheckStateRole:// <- то что надо 
            shape()->setVisible(value.value<Qt::CheckState>() == Qt::Checked);
            return true;
        case Qt::EditRole:
            if (auto text = dynamic_cast<Text*>(shape()); text)
                text->setText(value.toString());
            return true;
        default:
            return false;
        }
    case 1:
        if (auto text = dynamic_cast<Text*>(shape()); text) {
            switch (role) {
            case Qt::EditRole:
                text->setSide(static_cast<Side>(value.toBool()));
                return true;
            default:
                return false;
            }
        }
    default:
        return false;
    }
}
QVariant Node::data(const QModelIndex& index, int role) const
{
    switch (index.column()) {
    case 0:
        switch (role) {
        case Qt::DisplayRole:
            if (shape()->type() == GiShapeT)
                return QString("%1 (%2, %3)")
                    .arg(shape()->name())
                    .arg(m_id)
                    .arg(static_cast<Text*>(shape())->text());
            else
                return QString("%1 (%2)")
                    .arg(shape()->name())
                    .arg(m_id);
            //        case Qt::ToolTipRole:
            //            return file()->shortName() + "\n" + file()->name();
        case Qt::CheckStateRole:// <- то что надо 
            return shape()->isVisible() ? Qt::Checked : Qt::Unchecked;
        case Qt::DecorationRole:
            return shape()->icon();
        case Qt::UserRole:
            return m_id;
        case Qt::EditRole:
            if (shape()->type() == GiShapeT)
                return static_cast<Text*>(shape())->text();
            return QVariant();
        default:
            return QVariant();
        }
    case 1:
        if (auto text = dynamic_cast<Text*>(shape()); text) {
            switch (role) {
            case Qt::DisplayRole:
            case Qt::ToolTipRole:
                return sideStrList[text->side()];
            case Qt::EditRole:
                return static_cast<bool>(text->side());
            default:
                return QVariant();
            }
        }
    default:
        return QVariant();
    }
}

Qt::ItemFlags Node::flags(const QModelIndex& index) const
{
    Qt::ItemFlags itemFlag = Qt::ItemIsEnabled | Qt::ItemNeverHasChildren | Qt::ItemIsSelectable /*| Qt::ItemIsDragEnabled*/;
    switch (index.column()) {
    case 0:
        return itemFlag | Qt::ItemIsUserCheckable // <- то что надо 
            | (shape()->type() == GiShapeT
                    ? Qt::ItemIsEditable
                    : Qt::NoItemFlags);
    case 1:
        return itemFlag
            | (shape()->type() == GiShapeT
                    ? Qt::ItemIsEditable
                    : Qt::NoItemFlags);
    default:
        return itemFlag;
    }
}

И не надо ни какой мороки с делегатами. Смотреть на строки с комментом "// <- то что надо"

Evgenii Legotckoi
  • Sept. 20, 2020, 4:34 p.m.
  • (edited)

До тех пор, пока у вас проект содержит только одну таблицу, или несколько то может быть.
Когда их будет 1000 и чекбоксы в разных колонках, то без делегатов и переопределения возвращаемых редакторов в ячейках не обойдётесь )))

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 11:56 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 11:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 11:35 a.m.

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

  • Result:73points,
  • Rating points1
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
G
GarApril 22, 2024, 12:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 2:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 1:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 9:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 11:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks