Hi, I encounter a problem in create a checkbox column in QTableView

I create a checkbox only column in QTableView with delegate and model. The checkbox works fine, however the background color of the checkbox is not responsible for selection. When a row selected, the background color of the cells in this row will be dark blue. But the check box cell's background color is still white. I need it to be responsible for selection. It is looked like as the snap picture. The code is also put below.

So, how should I do to make the check box cell show the right background color when selected?

table.png

The code of paint() in deletegate:

Qt Code:
  1. void CheckBoxDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
  2. {
  3. bool data = index.model()->data(index, Qt::DisplayRole).toBool();
  4. QStyleOptionButton checkboxstyle;
  5. QRect checkbox_rect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkboxstyle);
  6. checkboxstyle.rect = option.rect;
  7. checkboxstyle.rect.setLeft(option.rect.x() + option.rect.width()/2 - checkbox_rect.width()/2);
  8. checkboxstyle.palette.setColor(QPalette::Highlight, index.data(Qt::BackgroundRole).value<QColor>());
  9. if(data)
  10. checkboxstyle.state = QStyle::State_On|QStyle::State_Enabled;
  11. else
  12. checkboxstyle.state = QStyle::State_Off|QStyle::State_Enabled;
  13. QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkboxstyle, painter);
  14. }
To copy to clipboard, switch view to plain text mode 

I also reimplement date(), setdata() and flags() in model:
Qt Code:
  1. QVariant UniqueCheckRowModel::data( const QModelIndex &index, int role /*= Qt::DisplayRole*/ ) const
  2. {
  3. QVariant value = QSqlRelationalTableModel::data(index,role);
  4.  
  5.  
  6. if (role == Qt::CheckStateRole && index.column() == colNumberWithCheckBox)
  7. {
  8. return (QSqlRelationalTableModel::data(index).toInt() != 0) ? Qt::Checked : Qt::Unchecked;
  9. }
  10. return value;
  11. }
  12.  
  13. Qt::ItemFlags UniqueCheckRowModel::flags( const QModelIndex &index ) const
  14. {
  15. Qt::ItemFlags flags = QSqlRelationalTableModel::flags(index);
  16. if (index.column() == colNumberWithCheckBox)
  17. {
  18. flags |= Qt::ItemIsUserCheckable;
  19. flags |= Qt::ItemIsSelectable;
  20. }
  21. else
  22. {
  23. flags |= Qt::ItemIsEditable;
  24. flags |= Qt::ItemIsSelectable;
  25. }
  26. return flags;
  27. }
  28.  
  29. bool UniqueCheckRowModel::setData( const QModelIndex &index, const QVariant &value, int role = Qt::EditRole )
  30. {
  31. if (index.column() == colNumberWithCheckBox)
  32. {
  33. role = Qt::CheckStateRole;
  34. }
  35. QSqlRelationalTableModel::setData(index,value);
  36. return true;
  37. }
To copy to clipboard, switch view to plain text mode