QTableView: Checkbox is not editable



  • Hi,

    i´m trying to show a Checkbox in my QTableView ( instead of the value ( 0 / 1 ) of the database ). Therefore i´ve written my own Model, in which i´ve overwritten flags(), setdata() and data():

    The Checkbox is shown, but is not editable, nothing happens when i click on the Box. Can you help me here? I dont understand why.

    Regards
    Achim

    Qt::ItemFlags CinemaModel::flags(const QModelIndex &index) const
    {
    	if (index.column() == 4)
    	{
    	return  Qt::ItemIsUserCheckable | Qt::ItemIsEnabled;
    	}
    
    	return QSqlQueryModel::flags(index);
    }
    
    
    QVariant CinemaModel::data(const QModelIndex & index, int role) const
    {
    	if( index.column() == 4 && role == Qt::CheckStateRole )
    	{
    		if (role == Qt::CheckStateRole)
    		{
    			return index.data(Qt::EditRole).toBool() ? QVariant(Qt::Checked) : QVariant(Qt::Unchecked);
    		}		
    	}
    	return QSqlQueryModel::data(index, role);
    }
    
    
    bool CinemaModel::setData(const QModelIndex &index, const QVariant &value, int role)
    {
    	if (index.column() == 4)
    	{
    		QVariant data = value.toInt() == Qt::Checked ? QVariant(true) : QVariant(false);
    		return QSqlQueryModel::setData(index, data, Qt::EditRole);
    	}
    	
    	return QSqlQueryModel::setData(index, value, role);	
    }
    

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    AFAIR, with the set of flags you return, your item will not be editable.

    You should rather have something like:

    Qt::ItemFlags CinemaModel::flags(const QModelIndex &index) const 
    {
        Qt::ItemFlags result = QSqlTableModel::flags(index);
        if (index.column() == 4) {
            result |= Qt::ItemIsUserCheckable;
        }
        return result;
    }
    

    Note that QSqlQueryModel is a read-only model so you may have to also add the Qt::ItemIsEditable flag.



  • THX SGaist for the hint with the read-only model, i didn´t noticed it. Now, i use a QSqlTableModel instead of a QueryModel and it woks, while using the right flags...

    Only one problem left...I must doubeblick on the cell with the checkbox, so the checkbox gets the focus. And then i can can check/uncheck it. Do you / anyone know a solution, with which i can change the state with only one click? I´ve tried already to ovveride the mousePressEvent(), but iz didnt worked :/

    Regards
    Achim


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.