Чтобы создать на Qt работающий пример добавления пунктов checkbox в ячейки таблицы Tableview без использования базы данных следует создать файлы класса для делегата – например delegate.h и delegate.cpp.
#ifndef CHECKBOXDELEGATE_H
#define CHECKBOXDELEGATE_H
#include "QStyledItemDelegate"
class CheckBoxDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
CheckBoxDelegate(QObject *parent = nullptr);
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
#include "delegate.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 - 0 или 1
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);
}
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "QMainWindow"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
void tableviewfunction();//основная функция, выводящая таблицу в tableView
void forworktableview();//получение индекса ячейки в tablevidget через checkbox или radiobutton
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "delegate.h"
#include "QTableView"//добавлено для вывода БД в таблице
#include "QStandardItemModel"//добавлено для вывода БД в таблице
#include "QStandardItem"//добавлено для вывода БД в таблице
#include "QCheckBox"//добавлено для вывода QCheckBox в таблице
#include "QRadioButton"//добавлено для вывода QRadioButton в таблице
#include "QStyledItemDelegate"
#include "QStandardItemModel"
#include "QHeaderView"
#include "QTableView"
#include "QDebug"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tableviewfunction();//основная функция, выводящая таблицу в tableView
connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(forworktableview()));//получение значений всех ячеек в tableview через выбранные checkbox и radiobutton
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::tableviewfunction(){//основная функция, выводящая таблицу в tableView
QTableView *tableView = ui->tableView;
CheckBoxDelegate *delegate = new CheckBoxDelegate();
int columndelegatenumber=0;//номер колонки для делегата
int countrows=10;//кол-во строк
int countcolumns=2;//кол-во колонок
QStandardItemModel *model = new QStandardItemModel(countrows, countcolumns);
//Заполнить таблицу данными
for (int row =0; row < countrows; ++row) {
for (int column = 0; column < countcolumns; ++column) {
QModelIndex index = model->index(row, column, QModelIndex());
if(column == columndelegatenumber)
{
model->setData(index, QVariant(0));
//если установить значение 0 в колонку 0 - выставится НЕнажатый checkbox
//если установить значение 1 и больше в колонку 0 - выставится нажатый checkbox
}
else
{
model->setData(index, QVariant((row + 1) * (column + 1)));
}
}
}
//Устанавливаем модель в представление
tableView->setModel(model);
//Устанавливаем делегат в столбец
tableView->setItemDelegateForColumn(columndelegatenumber, delegate);
//Внешний вид представления
tableView->resizeColumnsToContents();
tableView->verticalHeader()->hide();
tableView->horizontalHeader()->setStretchLastSection(true);
}
void MainWindow::forworktableview(){//получение значения ячейки в tableview через checkbox или radiobutton
int countrows=ui->tableView->model()->rowCount();
//int countcolumns=ui->tableView->model()->columnCount();
QString a[countrows];//создание массива с количеством элементов countrows
//Получить данные
for (int row =0; row < countrows; ++row) {
QModelIndex index = ui->tableView->model()->index(row, 0, QModelIndex());//установка индекса - 0 колонка в каждой строке
QVariant value=ui->tableView->model()->data(index);//поместить в переменную значение ячейки
//так как там установлен делегат для checkbox должны быть значения
//1 - если нажат checkbox и 0 - если не нажат checkbox
//qDebug() << "информация = " << value;//вывод содержимого ячеек с индексом index(row, 0, QModelIndex())
if(value==1){//если нажата галочка, внести значения в мвссив
QModelIndex index1 = ui->tableView->model()->index(row, 1, QModelIndex());//установка индекса - 1 колонка в каждой строке
QVariant value1=ui->tableView->model()->data(index1);//поместить в переменную значение ячейки
qDebug() << "выбрано значение в формате QVariant = " << value1;////вывод содержимого ячеек с индексом index(row, 1, QModelIndex())
QString x = value1.toString();//перевод из QVariant в тип QString
a[row]=x;//для простоты внесения в массив, используется int row, так как тоже идет по порядку
qDebug() << "элементы массива = "<< a[row];//Вывести элементы массива
}
}
}
Чтобы создать на Qt работающий пример добавления пунктов checkbox в ячейки таблицы Tableview без использования базы данных следует создать файлы класса для делегата – например delegate.h и delegate.cpp.
#ifndef CHECKBOXDELEGATE_H
#define CHECKBOXDELEGATE_H
#include "QStyledItemDelegate"
class CheckBoxDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
CheckBoxDelegate(QObject *parent = nullptr);
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
#include "delegate.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 - 0 или 1
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);
}
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "QMainWindow"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
void tableviewfunction();//основная функция, выводящая таблицу в tableView
void forworktableview();//получение индекса ячейки в tablevidget через checkbox или radiobutton
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "delegate.h"
#include "QTableView"//добавлено для вывода БД в таблице
#include "QStandardItemModel"//добавлено для вывода БД в таблице
#include "QStandardItem"//добавлено для вывода БД в таблице
#include "QCheckBox"//добавлено для вывода QCheckBox в таблице
#include "QRadioButton"//добавлено для вывода QRadioButton в таблице
#include "QStyledItemDelegate"
#include "QStandardItemModel"
#include "QHeaderView"
#include "QTableView"
#include "QDebug"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tableviewfunction();//основная функция, выводящая таблицу в tableView
connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(forworktableview()));//получение значений всех ячеек в tableview через выбранные checkbox и radiobutton
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::tableviewfunction(){//основная функция, выводящая таблицу в tableView
QTableView *tableView = ui->tableView;
CheckBoxDelegate *delegate = new CheckBoxDelegate();
int columndelegatenumber=0;//номер колонки для делегата
int countrows=10;//кол-во строк
int countcolumns=2;//кол-во колонок
QStandardItemModel *model = new QStandardItemModel(countrows, countcolumns);
//Заполнить таблицу данными
for (int row =0; row < countrows; ++row) {
for (int column = 0; column < countcolumns; ++column) {
QModelIndex index = model->index(row, column, QModelIndex());
if(column == columndelegatenumber)
{
model->setData(index, QVariant(0));
//если установить значение 0 в колонку 0 - выставится НЕнажатый checkbox
//если установить значение 1 и больше в колонку 0 - выставится нажатый checkbox
}
else
{
model->setData(index, QVariant((row + 1) * (column + 1)));
}
}
}
//Устанавливаем модель в представление
tableView->setModel(model);
//Устанавливаем делегат в столбец
tableView->setItemDelegateForColumn(columndelegatenumber, delegate);
//Внешний вид представления
tableView->resizeColumnsToContents();
tableView->verticalHeader()->hide();
tableView->horizontalHeader()->setStretchLastSection(true);
}
void MainWindow::forworktableview(){//получение значения ячейки в tableview через checkbox или radiobutton
int countrows=ui->tableView->model()->rowCount();
//int countcolumns=ui->tableView->model()->columnCount();
QString a[countrows];//создание массива с количеством элементов countrows
//Получить данные
for (int row =0; row < countrows; ++row) {
QModelIndex index = ui->tableView->model()->index(row, 0, QModelIndex());//установка индекса - 0 колонка в каждой строке
QVariant value=ui->tableView->model()->data(index);//поместить в переменную значение ячейки
//так как там установлен делегат для checkbox должны быть значения
//1 - если нажат checkbox и 0 - если не нажат checkbox
//qDebug() << "информация = " << value;//вывод содержимого ячеек с индексом index(row, 0, QModelIndex())
if(value==1){//если нажата галочка, внести значения в мвссив
QModelIndex index1 = ui->tableView->model()->index(row, 1, QModelIndex());//установка индекса - 1 колонка в каждой строке
QVariant value1=ui->tableView->model()->data(index1);//поместить в переменную значение ячейки
qDebug() << "выбрано значение в формате QVariant = " << value1;////вывод содержимого ячеек с индексом index(row, 1, QModelIndex())
QString x = value1.toString();//перевод из QVariant в тип QString
a[row]=x;//для простоты внесения в массив, используется int row, так как тоже идет по порядку
qDebug() << "элементы массива = "<< a[row];//Вывести элементы массива
}
}
}