Search code examples
c++qtqwidgetqtablewidgetqcheckbox

Qt - Access a checkbox in a table


I have a table and each row in the table has a checkbox in it's first column. I need to make it so I can detect which checkboxes are checked and delete those rows when a button is pressed.

QWidget * chkWidget = new QWidget();
QHBoxLayout *center = new QHBoxLayout();
center->setAlignment( Qt::AlignCenter );
center->addWidget( new QCheckBox );
chkWidget->setLayout( center );
ui->data_table->setCellWidget(rowCount,0, chkWidget);

Was this done right? If so how do I access the checkboxes at each row?


Solution

  • I talk about a QTableWidget. You can use a QList.You save your QCheckBox into this QList and use it, when there is some change

    Maybe you should check out the documentation

    Here is a solution. I cannot run it at the moment, so please tell me if it works. Please validate the row value. I am not sure if it's possible, that row can have the value -1 when you delete the last row ;)

    #include "TestTableWidget.h"
    #include "ui_TestTableWidget.h"
    
    TestTableWidget::TestTableWidget(QWidget *parent) : QMainWindow(parent), ui(new Ui::TestTableWidget)
    {
        ui->setupUi(this);
    
        tableWidget = new QTableWidget(this);
        tableWidget->setColumnCount(1); // Just an example
    
        ui->gridLayout->addWidget(tableWidget);
    
        connect(tableWidget, SIGNAL(itemSelectionChanged()), this, SLOT(slotChange()));
    
        for(int i = 1; i < 10; i++)
        {
            addRow("Row " + QString::number(i));
        }
    }
    
    TestTableWidget::~TestTableWidget()
    {
        delete ui;
    }
    
    void TestTableWidget::addRow(QString text)
    {
        int row = tableWidget->rowCount();
        qDebug() << "Current row count is " + QString::number(row);
    
        // Add new one
        QTableWidgetItem *item = new QTableWidgetItem(text);
        tableWidget->insertRow(row);
        tableWidget->setItem(row, 0, item);
    
        // Add item to our list
    }
    
    void TestTableWidget::slotChange()
    {
        int row = tableWidget->currentRow();
        qDebug() << "Change in table. Current row-index: " + QString::number(row);
        // This value is zero-based, so you can use it in our list
    }