rrrfusco
rrrfusco

Reputation: 1119

Qt checkboxes in QTableView

I'm using this code to query sqlite and put the results in a QTableView.

//MainWindow.cpp
void MainWindow::on_pushButton_clicked()
{
    QSqlQueryModel * modal=new QSqlQueryModel();
    connOpen();
    QSqlQuery* qry=new QSqlQuery(mydb);

    qry->prepare("select * from database");
    qry->exec();

    modal->setQuery(*qry);

    //from stack
    modal->insertColumn(0);

    ui->tableView->setModel(modal);

    //from stack
    ui->tableView->resizeColumnsToContents();

    int p;
    for(p=0; p<modal->rowCount(); p++)
    {
        ui->tableView->setIndexWidget(modal->index(p,0),new QCheckBox());
    }

    connClose();
    qDebug() <<(modal->rowCount());
}

I've seen several examples of the web for adding checkboxes to a column, but I'm not quite sure what to use for my simple example.

What I intend to do is to have column 1 checkable. On next btn press, If checked those rows of data get written to a file.

I still need to understand how to loop thru the selected data, or perhaps I need to get the ids of the checked rows and do another query.

Questions:

Upvotes: 4

Views: 13514

Answers (1)

Fabio
Fabio

Reputation: 2602

I think the best way to have a column of checkable cells is to create your item model, e.g. by subclassing the QSqlQueryModel. You must reimplement the flags() method to make checkable the cells.

Also you need to reimplement the data() method to return the check state and the setData() method and to set the check state. You must implement your own logic to keep track of the check state of every rows (e.g. using an array of Qt::CheckState that you must initialize and resize when the model data changes).

Yuo can start with something like this:

class MyModel : public QSqlQueryModel
{
public:

    Qt::ItemFlags flags(const QModelIndex & index) const
    {
        if(index.column() == 0)
             return QSqlQueryModel::flags(index) | Qt::ItemIsUserCheckable;
        return QSqlQueryModel::flags(index);
    }

    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const 
    {
        if(index.column() == 0 && role == Qt::CheckStateRole)
        {
            //implement your logic to return the check state 
            //....
        }
        else
            return QSqlQueryModel::data(index, role);
    }

    bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole)
    {
        if(index.column() == 0 && role == Qt::CheckStateRole)
        {
            //implement your logic to set the check state 
            //....
        }
        else
            QSqlQueryModel::setData(index, value, role);
    }
};

Se also:

Upvotes: 6

Related Questions