Qt checkboxes in QTableView

前端 未结 1 1683
余生分开走
余生分开走 2021-01-14 10:15

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

//MainWindow.cpp
void MainWindow::on_pushButton_clicked()
{
    QSqlQueryModel * m         


        
相关标签:
1条回答
  • 2021-01-14 10:40

    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:

    • Model Subclassing
    • QAbstractItemModel documentation
    0 讨论(0)
提交回复
热议问题