0

I have a QTableView that shows QSqlQueryModel. The model contains checkboxes that are created in each row in the first column (which contain the ref_no; the primary-key in my db) as follow:

void MainWindow::showM(model){
    ui->tableView->setModel(model);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    for( int i = 0; p<model->rowCount(); i++)
    {
        QCheckBox *checkBox = new QCheckBox();
        ui->tableView->setIndexWidget(model->index(i,0),checkBox);
    }
    ui->tableView->show();
}

... and it's working fine, displaying all the information I need plus the checkboxes.

Now, I need to get the ref_no where the adjacent checkbox is checked.

How to do that ?

McLan
  • 2,552
  • 9
  • 51
  • 85

1 Answers1

1

Use QSignalMapper (or an ad hoc solution involving a mapper using sender(), or lambdas). For instance define a member for the mapping:

QHash<QCheckBox *, int> m_mapping;

Then in your code hook it up like this:

QCheckBox *checkBox = new QCheckBox();
ui->tableView->setIndexWidget(model->index(i,0),checkBox);
m_mapping[checkBox] = i;
connect(checkBox, &QCheckBox::toggled, this, &MainWindow::onCheckBoxToggled);

Then define a slot like this:

// for the love of kittens use proper names for methods
void MyWindow::onCheckBoxToggled(bool toggled) {
    QCheckBox *box = static_cast<QCheckBox *>(sender());
    const int id = m_mapping.value(box);
    // do something
}

Or, if you fancy lambdas, you can do the above with a capture:

connect(checkBox, &QCheckBox::toggled, 
        [i](bool toggled){ /* use i, toggled */ });

All of that having being said, I would strongly recommend against the idea of creating QCheckBoxes and using setIndexWidget. Instead, employ a proxy model that enriches your column by returning the Qt::ItemIsUserCheckable flag and handles reads and writes for the Qt::CheckStateRole.

peppe
  • 21,934
  • 4
  • 55
  • 70