Reputation: 53
I m new to Qt
and i m trying to add a QCheckbox
Column to my QTableView
using SetIndexWidget()
as follows:
QSqlQueryModel * model = new QSqlQueryModel();
model->setQuery("select * from Rendezvous");
model->insertColumn(0);
model->setHeaderData(0, Qt::Horizontal, QObject::tr(""));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("Date"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("Heure"));
model->setHeaderData(4, Qt::Horizontal, QObject::tr("Type"));
model->setHeaderData(5, Qt::Horizontal, QObject::tr("Description"));
model->setHeaderData(6, Qt::Horizontal, QObject::tr("ID Client"));
ui->tableView_RDV->setModel(model);
ui->tableView_RDV->resizeColumnToContents(0);
for(int p=0;p<model->rowCount();p++)
{
ui->tableView_RDV->setIndexWidget(model->index(p,0),new QCheckBox());
}
This adds a Checkbox to my Table and i can interact with it but i have no idea how to check Which Lines in my QTableView
have Checked QCheckboxe
s.
I appreciate any kind of indication to how to do this.
Upvotes: 1
Views: 900
Reputation: 4104
Following code snippet may help you:
for(int p=0;p<model->rowCount();p++)
{
QCheckBox* tmp = qobject_cast<QCheckBox*>(ui->tableView_RDV->indexWidget(model->index(p,0)));
if(tmp != NULL && tmp.isChecked())
{
//Do what you wants when it is checked
}
}
UPDATED
For using qobject_cast
instead of dynamic_cast
after comment from Dmitry Sazonov and information available at Qt Forum
Upvotes: 0
Reputation: 9014
You should use Qt::CheckStateRole
for displaying checkboxes. It is much faster, and corresponds to Qt MVC:
for(int p=0;p<model->rowCount();p++)
{
auto checked = SomeLogic ? Qt::Checked : Qt::Unchecked;
auto index = model->index( p, 0 );
model->setData( index, checked, Qt::CheckStateRole );
}
Note: checkbox will be shown only if you directy specify Qt::CheckStateRole
with non-empty value. If you will set it to an empty QVariant()
, checkbox will not be shown.
Upvotes: 1